Java 整数超出范围
Java Integer out of range
我正在学习 Java 并且正在尝试一些小程序。
我对此有疑问:
/*
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
为什么输出是1507852288?
应该是2,147,483,647.
谢谢。
当一个int运算的结果(比如乘法)高于最大int值时,它会溢出(即不适合一个int变量的32位),这意味着赋值给int 变量不正确。如果正确结果更高,你没有理由期望它 return 最大 int 值。
如果您想要正确的结果,请使用多头。
当结果超过 int 的最大值时,它就会溢出,即 integer overflow。您最好使用 long
而不是 int
.
您可能有兴趣阅读:Integer overflow and underflow in Java.
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 并且正在尝试一些小程序。 我对此有疑问:
/*
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
为什么输出是1507852288? 应该是2,147,483,647.
谢谢。
当一个int运算的结果(比如乘法)高于最大int值时,它会溢出(即不适合一个int变量的32位),这意味着赋值给int 变量不正确。如果正确结果更高,你没有理由期望它 return 最大 int 值。
如果您想要正确的结果,请使用多头。
当结果超过 int 的最大值时,它就会溢出,即 integer overflow。您最好使用 long
而不是 int
.
您可能有兴趣阅读:Integer overflow and underflow in Java.
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.