簡體   English   中英

為什么這段代碼打印負數?

[英]Why is this code printing a negative number?

public class Program {
    public static void main(String[] args) {
        int x = 1;
        for (int i = 1; i < 31; i++) {
            x = x + 2 * x;
        }
        System.out.println(x);
    }
}

它打印 -1010140999,我不知道為什么它是負數。

最終輸出是一個非常長的數字,將超過最大整數容量。 因此我們需要使用長數據類型。 請在每次迭代時使用 x 值檢查下面的正確代碼

public class Program {
    public static void main(String[] args) {
        long x = 1;
        for (int i = 1; i < 31; i++) {
            x = x + 2l * x;
            System.out.println(i+ " " +x);
        }
    }
}

輸出

1 3
2 9
3 27
4 81
5 243
6 729
7 2187
8 6561
9 19683
10 59049
11 177147
12 531441
13 1594323
14 4782969
15 14348907
16 43046721
17 129140163
18 387420489
19 1162261467
20 3486784401
21 10460353203
22 31381059609
23 94143178827
24 282429536481
25 847288609443
26 2541865828329
27 7625597484987
28 22876792454961
29 68630377364883
30 205891132094649

Java 中的整數以 32 位存儲,其中一位用於指示值是正數還是負數。 這意味着int的值介於 -2^31 和 2^31 - 1 之間。

一旦你加或減超過這些限制,你就會在相應的方向回繞,因為發生了上溢/下溢。

public class OverflowExample {
    public static void main(String args[]) {
        int largest_int  = Integer.MAX_VALUE;
        int smallest_int = Integer.MIN_VALUE;
        
        System.out.println(largest_int);     //  2ˆ31 - 1 = 2147483647
        System.out.println(largest_int + 1); // -2147483648
        System.out.println(smallest_int);    // -2^31, same as above
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM