gpt4 book ai didi

java - System.out.println(4*2147483647) 在java中如何等于-4?

转载 作者:搜寻专家 更新时间:2023-10-31 08:04:53 24 4
gpt4 key购买 nike

我是 Java 初学者,对此很困惑。

System.out.println(4*2147483647) 在java中如何等于-4?

最佳答案

这是由于整数静默溢出。

2147483647 == Integer.MAX_VALUE 是整数的最大值。

静默溢出意味着 2147483647 + 1 == Integer.MIN_VALUE = -2147483648
然后你可以看到 2147483647 + 2147483647 == 2147483647 + (-2147483648 + - 1) == -2

换句话说,2147483647 * 2 == -2,您现在可以明白为什么 2147483647 * 4 == -4

从技术上讲,结果由 Java Language Specification #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.

关于java - System.out.println(4*2147483647) 在java中如何等于-4?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11795522/

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