gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:43:16 28 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

为什么打印两个相同大小的负数而不是正数和负数?

最佳答案

由于静默整数溢出: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/25723186/

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