当您运行以下代码时
count
的值变为-1,程序以零除以异常结束。
取消注释sysout
时,它运行良好。不确定sysout
如何产生差异。
public class HelloWorld{
public static void main(String []args){
int num = 1;
int count;
int sum;
int fact;
for(count=1,sum=0,fact=1;fact<=num;count=count+1){
//System.out.println("num:"+num+" fact:"+fact+" count:"+count+" sum:"+sum);
if(num%count==0){
fact = num/count;
sum = sum+fact;
System.out.println("num:"+num+" fact:"+fact+" count:"+count+" sum:"+sum);
}
}
}
}
输出:
num:1事实:1 count:1 sum:1
num:1事实:-1 count:-1 sum:0
线程“ main”中的异常java.lang.ArithmeticException:/减零在HelloWorld.main(HelloWorld.java:14)
当计数值变得大于Integer.MAX_VALUE时,该计数被定义为整数。它溢出并变为负数。
作为(大于1的1%,任何大于1的数字)不能为零,因此循环继续进行并且计数值不断增长,并且在Integer.MAX_VALUE循环后溢出。
您不断增加计数,最终溢出并环绕到0
。
In binary, Integer.MAX_VALUE = 2147483647 = 01111111 11111111 11111111 11111111
^
sign bit (positive)
When you add one more to the number it becomes
Integer.MIN_VALUE = -2147483648 = 1000000 000000 000000 000000 000000
^
sign bit (negative)
因此它环绕并且从Integer.MAX_VALUE到Integer.MIN_VALUE。
for(int count=Integer.MAX_VALUE -10; count != Integer.MIN_VALUE + 10; count++){
System.out.println("count = " + count);
}
如您所见,如果继续将1
添加到count
,它将最终增加到0
,并且得到0
除以错误。
您可以在Wikipedia上阅读有关Two's Complement Representation的更多信息。>>