System.out.println(4 * 2147483647)在Java中如何等于-4? [英] How is System.out.println(4*2147483647) equal to -4 in java?
问题描述
我是Java初学者,对此颇为困惑.
I am a Java beginner and pretty confused with this.
System.out.println(4 * 2147483647)
在Java中如何等于-4?
How is System.out.println(4*2147483647)
equal to -4 in java?
推荐答案
这是由于整数静默溢出造成的.
It is due to integer silent overflow.
2147483647 == Integer.MAX_VALUE
是整数的最大值.
严重溢出意味着 2147483647 + 1 == Integer.MIN_VALUE = -2147483648
然后您可以看到 2147483647 + 2147483647 == 2147483647 +(-2147483648 +1-== -2
换句话说, 2147483647 * 2 == -2
,现在您可以了解为什么 2147483647 * 4 == -4
.
In other words, 2147483647 * 2 == -2
, and you can now see why 2147483647 * 4 == -4
.
从技术上讲,结果由定义Java语言规范#15.17.1 :
如果整数乘法溢出,则结果是数学乘积的低阶位,以某种足够大的二进制补码格式表示.结果,如果发生溢出,则结果的符号可能与两个操作数值的数学乘积的符号不同.
If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format. As a result, if overflow occurs, then the sign of the result may not be the same as the sign of the mathematical product of the two operand values.
这篇关于System.out.println(4 * 2147483647)在Java中如何等于-4?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!