为什么i = i +我给我0? [英] Why does i = i + i give me 0?
问题描述
我有一个简单的程序:
public class Mathz {
static int i = 1;
public static void main(String[] args) {
while (true){
i = i + i;
System.out.println(i);
}
}
}
当我运行此程序时,我看到的只是 0
我输出中的 i
。我原本预计第一次会有 i = 1 + 1
,然后是 i = 2 + 2
,然后是 i = 4 + 4
等。
When I run this program, all I see is 0
for i
in my output. I would have expected the first time round we would have i = 1 + 1
, followed by i = 2 + 2
, followed by i = 4 + 4
etc.
这是因为我们一试要在左侧重新声明 i
,其值将重置为 0
?
Is this due to the fact that as soon as we try to re-declare i
on the left hand-side, its value gets reset to 0
?
如果有人能指出我的更精细的细节,那就太棒了。
If anyone can point me into the finer details of this that would be great.
更改 int
到 long
,它似乎是按预期打印数字。我对它达到最大32位值的速度感到惊讶!
Change the int
to long
and it seems to be printing numbers as expected. I'm surprised at how fast it hits the max 32-bit value!
推荐答案
问题是整数溢出造成的。
The issue is due to integer overflow.
在32位二进制补码算术中:
In 32-bit twos-complement arithmetic:
i
确实开始具有两个幂的值,但是一旦你到达2 30 ,溢出行为就开始了:
i
does indeed start out having power-of-two values, but then overflow behaviors start once you get to 230:
2 30 + 2 30 = -2 31
230 + 230 = -231
-2 31 + -2 31 = 0
-231 + -231 = 0
... in int
算术。
...in int
arithmetic.
这篇关于为什么i = i +我给我0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!