简体   繁体   English

Java Integer超出范围

[英]Java Integer out of range

I'm learning Java and I'm trying little programs. 我正在学习Java,而我正在尝试一些小程序。 I have a problem with this one: 我有这个问题:

/*
 Compute the number of cubic inches
 in 1 cubic mile.
*/
class Inches {
    public static void main(String args[]) {
        int ci;
        int im;

        im = 5280 * 12;

        ci = im * im * im;

        System.out.println("There are " + ci + " cubic inches in cubic mile.");
    }
}

The output is: 输出是:

There are 1507852288 cubic inches in cubic mile.

I known the width in bits for a integer is 32, so the range is: -2,147,483,648 to 2,147,483,647 我知道整数的位宽是32,所以范围是:-2,147,483,648到2,147,483,647

Why is the output 1507852288? 为什么输出1507852288? It should be 2,147,483,647. 它应该是2,147,483,647。

Thank you. 谢谢。

When the result of an int operation (such as multiplication) is higher than the max int value, it overflows (ie doesn't fit within the 32 bits of an int variable), which means the value assigned to the int variable is incorrect. 当int操作(例如乘法)的结果高于max int值时,它会溢出(即不适合int变量的32位),这意味着赋给int变量的值不正确。 You have no reason to expect it to return the max int value if the correct result is higher. 如果正确的结果更高,您没有理由期望它返回max int值。

If you want a correct result, use longs. 如果您想要正确的结果,请使用longs。

When the result crosses the maximum values of an int then it is overflowed ie, integer overflow . 当结果超过int的最大值时,它会溢出,即整数溢出 You may better want to use long instead of int . 您可能最好使用long而不是int

You may be interested to read: Integer overflow and underflow in Java. 您可能有兴趣阅读: Java中的整数溢出和下溢。

Arithmetic integer operations are performed in 32-bit precision. 算术整数运算以32位精度执行。 When the resultant value of an operation is larger than 32 bits (the maximum size an int variable can hold) then the low 32 bits only taken into consideration and the high order bits are discarded. 当操作的结果值大于32位(int变量可以保持的最大大小)时,仅考虑低32位并丢弃高位。 When the MSB (most significant bit) is 1 then the value is treated as negative. 当MSB(最高有效位)为1时,该值被视为负值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM