学习JAVA,我试图测试while循环的上限继续增加int.请参阅下面的程序:
public class Test {
public static int a(){
int a = 10;
while(a > 9 )
++a;
return a;
}
public static void main(String[] argc) {
Test t = new Test();
int k = t.a();
System.out.println("k = "+(1 * k));
}
}
Run Code Online (Sandbox Code Playgroud)
我知道32位的范围是-2,147,483,648到2,147,483,647,所以在此基础上,我期待输出,2,147,483,647但我得到:
k = -2147483648
Run Code Online (Sandbox Code Playgroud)
我甚至试过了
System.out.println("k = "+(1 * k/2));
Run Code Online (Sandbox Code Playgroud)
但仍然输出是:
k = -1073741824
Run Code Online (Sandbox Code Playgroud)
题 :
为什么解决方案是负面的,应该是积极的?
你正在递增你a int的1直到达到1 + Integer.MAX_VALUE,它将其值转换为-2147483648 == Integer.MIN_VALUE.
这是你的循环评论:
// "infinite" loop as a is assigned value 10
while(a > 9)
// when a reaches Integer.MAX_VALUE, it is still incremented by 1
++a;
// loop condition now false, as value for a has shifted to -2147483648
return a;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |