gpt4 book ai didi

Java Integer.MIN_VALUE 的负数然后比较产生两个负数

转载 作者:太空狗 更新时间:2023-10-29 22:42:53 24 4
gpt4 key购买 nike

我明天要考试,我看不懂我书上的解释,感谢帮助:

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 个大小相同的负数而不是正数和负数?

最佳答案

由于静默整数溢出:Integer.MIN_VALUE-2^31Integer.MAX_VALUE2^31- 1,所以-Integer.MIN_VALUE2^31,也就是Integer.MAX_VALUE + 1,根据定义也是对于整数来说很大。所以它溢出并变成Integer.MIN_VALUE...

您还可以检查:

System.out.println(Integer.MAX_VALUE + 1);

打印同样的东西。

从技术上讲,结果由 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 Integer.MIN_VALUE 的负数然后比较产生两个负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12535095/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com