Java整数Min_Value为负,然后比较 [英] Java Integers Min_Value negative then compare
问题描述
明天我有一个测试,我无法理解我的书籍解释,我很感激帮助:
I have a test tomorrow and I cant understand my books explanation, I appreciate the help:
public class TestClass{
public static void main(String[] args) throws Exception{
int a = Integer.MIN_VALUE;
int b = -a;
System.out.println( a+ " "+b);
}
}
输出: -2147483648 - 2147483648
为什么打印2个相同幅度的负数而不是正数和负数?
Why does this print 2 negative numbers of the same magnitude and not a positive and negative?
推荐答案
由于无提示整数溢出: Integer.MIN_VALUE
是 -2 ^ 31
和 Integer.MAX_VALUE
是 2 ^ 31-1
,所以 -Integer.MIN_VALUE
是 2 ^ 31
,这是 Integer.MAX_VALUE + 1
,根据定义,它对于整数来说太大了。所以它溢出并变成 Integer.MIN_VALUE
...
Because of silent integer overflow: Integer.MIN_VALUE
is -2^31
and Integer.MAX_VALUE
is 2^31-1
, so -Integer.MIN_VALUE
is 2^31
, which is Integer.MAX_VALUE + 1
, which by definition is too large for an integer. So it overflows and becomes Integer.MIN_VALUE
...
您还可以检查:
System.out.println(Integer.MAX_VALUE + 1);
打印相同的东西。
更多从技术上讲,结果由 Java语言定义规范#15.18.2 :
More technically, the result is defined by the Java Language Specification #15.18.2:
如果整数加法溢出,则结果是数学的低位以一些足够大的二进制补码格式表示的和。如果发生溢出,则结果的符号与两个操作数值的数学和的符号不同。
If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values.
这篇关于Java整数Min_Value为负,然后比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!