为什么递增Java int最终会导致负数? [英] Why does incrementing a Java int eventually result in a negative number?

查看:564
本文介绍了为什么递增Java int最终会导致负数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was trying to check different inputs and creating infinite loops in java and I found that once the int is getting incremented over the maximum limit it turns in to negative -2147482958. I am just increasing the int in infinite loop...

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

打印出的最后一个值是,

The last to value gets printed out is,

2147483337
-2147482958

现在,为什么会变为负数?

Now, Why does it goes to negative?

推荐答案


为什么它会变成否定的吗?

Why does it goes to negative?

因为这是指定在 int 计算溢出。

Because that is what is specified to happen in Java when an int calculation overflows.

JLS 15.18.2


如果整数加法溢出然后结果是数学和的低阶位,用一些足够大的二进制补码格式表示。如果出现溢出,那么结果的符号与两个操作数的数学和的符号不同值。






(这没有明确说明说溢出总是给出一个负数。它并不总是如此。但是,如果您应用该规则,它确实解释了为什么通过 +1 递增 Integer.MAX_VALUE 为您提供 Integer.MIN_VALUE ...)


(This doesn't explicitly say that overflow always gives a negative number. And it doesn't always. But if you apply the rule, it does explain why incrementing Integer.MAX_VALUE by +1 gives you Integer.MIN_VALUE ...)

这篇关于为什么递增Java int最终会导致负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆