我正在学习Java,并且正在尝试一些小程序. 我对此有疑问:
I'm learning Java and I'm trying little programs. 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."); } }输出为:
There are 1507852288 cubic inches in cubic mile.我知道整数的宽度(以位为单位)为32,因此范围是: -2,147,483,648至2,147,483,647
I known the width in bits for a integer is 32, so the range is: -2,147,483,648 to 2,147,483,647
为什么输出1507852288? 应该是2,147,483,647.
Why is the output 1507852288? It should be 2,147,483,647.
谢谢.
推荐答案当结果超过int的最大值时,则溢出,即整数溢出.您可能最好使用long而不是int.
When the result crosses the maximum values of an int then it is overflowed ie, integer overflow. You may better want to use long instead of int.
您可能有兴趣阅读: Java中的整数上溢和下溢. /a>
You may be interested to read: Integer overflow and underflow in Java.
算术整数运算以32位精度执行.什么时候 运算的结果值大于32位( 一个int变量可以容纳的最大大小),然后仅取低32位 考虑到这一点,高阶位将被丢弃.当MSB (最高有效位)为1,则该值被视为负数.
Arithmetic integer operations are performed in 32-bit precision. 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. When the MSB (most significant bit) is 1 then the value is treated as negative.
更多推荐
Java整数超出范围
发布评论