【发布时间】:2016-05-11 08:03:11
【问题描述】:
public class Test {
public static void main(String [] s) {
int x = 99999;
long y = 99999;
long res = x * x;
System.out.println("x^2 = " + res);
res = y * y;
System.out.println("y^2 = " + res);
}
}
Output:
x^2 = 1409865409
y^2 = 9999800001
看到上述代码段的输出,我真的很困惑。我希望得到相同(正确)的答案,但这里 x^2 实际上是错误的!
【问题讨论】:
-
您遇到了溢出。一旦
x达到Integer.MAX_VALUE的值,将+1添加到x将导致x蜂鸣Integer.MIN_VALUE。 -
在第一种情况下,您将两个整数相乘,然后转换为长整数,在第二种情况下,您将两个整数相乘
标签: java long-integer