[英]what's wrong with this program
I've a code snippet: 我有一个代码段:
class WhileTest
{
public static void main(String s[])
{
int x=12;
while(x<13)
{
x--;
}
System.out.println(x);
}
}
The output of the above program is: 2147483647
上面的程序的输出是: 2147483647
Why so? 为什么这样?
x
递减,然后下溢达到Integer.MAX_VALUE
Note that x = 12, and you keep subtracting. 请注意,x = 12,并且您继续减去。 This results in x always being less than 13. That is until Integer Overflow occurs (when x gets to the lowest possible int (Integer.MIN_VALUE)), and the number wraps around to the maximum possible integer (Integer.MAX_VALUE) which is greater than 13 and the loop ends. 这将导致x 始终小于13。即直到发生Integer Overflow(x达到最低可能的int(Integer.MIN_VALUE)),并且该数字回绕为最大可能的整数(Integer.MAX_VALUE)为止。大于13,循环结束。
you decrease x
each iteration. 您每次迭代减少x
。
when x = -2147483648
(which is the MIN_VALUE of Integer ) the next step of x--
will set x = +2147483647
(which is the MAX_VALUE of Integer ) because of the overflow (or underflow, however you call it). 当x = -2147483648
(它是Integer的MIN_VALUE )时,由于上溢(或下溢,但是您将其称为),因此x--
的下一步将设置x = +2147483647
(它是Integer的MAX_VALUE )。
and since 2147483647 < 13 = false
you will see the println
并且由于2147483647 < 13 = false
您将看到println
Each iteration reduces the size of x, so theoretically x will never be greater than or equal to 13, right? 每次迭代都会减小x的大小,因此理论上x永远不会大于或等于13,对吧?
Sure, if ints behave just like integers. 当然,如果int的行为就像整数一样。 But they don't. 但是他们没有。 Int's have a maximum and minimum size, because of how they stored in your computer. Int具有最大和最小大小,因为它们在计算机中的存储方式。 In Java, an int is a 32-bit signed number; 在Java中,int是32位带符号的数字。 an int's maximum size is 2^31-1; 一个int的最大大小为2 ^ 31-1; it's minimum size is -2^31. 最小大小为-2 ^ 31。
What happens when x is the minimum size, -2^31, in that loop? 如果x在该循环中为最小大小-2 ^ 31,会发生什么情况? -2^31 - 1 < 13, so why does the loop condition fail? -2 ^ 31-1 <13,为什么循环条件失败? That number can't be represented by an int. 该数字不能用int表示。 The way ints behave is that they wrap around. 整数的行为方式是它们环绕。
int x = Integer.MIN_VALUE; // x = -2^31
x--;
x == Integer.MAX_VALUE; //True. x == 2^31-1
2^21 - 1 is larger than 13, and the loop condition fails. 2 ^ 21-1大于13,并且循环条件失败。 The print statement is run when x is Integer.MAX_VALUE. 当x为Integer.MAX_VALUE时,运行print语句。 And what is the value of 2^31 - 1? 2 ^ 31-1的值是多少? 2147483647 2147483647
int值转到Integer.MIN_VALUE,下溢并转到您正在查看的Integer.MAX_VALUE。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.