java 为什么这个代码打印的是负数?

xe55xuns  于 2022-12-25  发布在  Java
关注(0)|答案(2)|浏览(220)
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,我不知道为什么它是负数。

bvpmtnay

bvpmtnay1#

最后的输出是一个很长的数字,将超过最大整数容量。因此,我们需要使用长数据类型。请检查下面的代码是否正确,每次迭代时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);
        }
    }
}

产出

46scxncf

46scxncf2#

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
    }
}

相关问题