Java for循环是否定的

Java for loop is negative

当您运行低于代码

  1. count值变为-1,程序以被零除异常结束。

  2. 当您取消注释 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 fact:1 count:1 sum:1

num:1 fact:-1 count:-1 sum:0

Exception in thread "main" java.lang.ArithmeticException: / by zero at HelloWorld.main(HelloWorld.java:14)

你不断增加计数,它最终溢出并环绕到 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 的错误。

您可以在维基百科上阅读更多关于 Two's Complement Representation 的信息。

计数值大于Integer.MAX_VALUE时定义为整数 它溢出并变为负值。

因为(1 % any number greater than 1) cannot be Zero, so the loop keeps continues and count value keeps growing and it overflow after Integer.MAX_VALUE loops.