gpt4 book ai didi

java - 为什么递增 Java int 最终会导致负数?

转载 作者:搜寻专家 更新时间:2023-11-01 04:02:11 25 4
gpt4 key购买 nike

我试图检查不同的输入并在 java 中创建无限循环,我发现一旦 int 的增量超过最大限制,它就会变成负值 -2147482958。我只是在无限循环中增加 int...

代码:

public static void infiniteLoop(){
for(int i=0;i>-1;i++){
i = i + 1000;
System.out.println(i);
}
}

打印出的最后一个值是,

2147483337
-2147482958

现在,为什么它会变成负值?

最佳答案

Why does it goes to negative?

因为当 int 计算溢出时,Java 规定会发生这种情况。

JLS 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."


(这并没有明确说明溢出总是给出负数。而且并非总是如此。但是如果您应用该规则,它确实解释了为什么将 Integer.MAX_VALUE 递增 +1 给你 Integer.MIN_VALUE ...)

关于java - 为什么递增 Java int 最终会导致负数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10968733/

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