繁体   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