1
int i = 3, j = 3;
for (; i++ == j--; i += 2, j -= 2) {
    do {
        i = i + j;
    } while (i % j != 0);
}
System.out.println(i);
System.out.println(j);

我尝试在 Eclipse 中调试它,结果如下:

  • 我,j
  • 3,3
  • 4,2
  • 6,2
  • 9,-1

由于上次for循环检查了i和j的值,它们不相等,为什么会跳出循环呢?不会是无限循环吗?

4

4 回答 4

1

它们彼此不相等,因此循环终止。如果它们相等,循环将不会终止,这是您的条件。

于 2013-02-21T06:20:51.483 回答
1
for (; ++i != --j; i += 2, j -= 2) {}

条件++i != --jor i++ != --jor++i != j--会导致死循环。

i++ 和 j-- 分别是后递增和递减,所以首先它会检查条件,然后递增值。

于 2013-02-21T06:23:35.683 回答
1

不,它不会进入无限循环
1. i 和 j 被初始化 (i=3, j=3)
2. 检查条件。在检查条件后,值会发生变化 (i=3, j=2) --> Post increment and post decrement
3. 在 do while 循环内.. i=4 和 j 保持不变 (j=2)
4. 的条件做while循环中断。as (6%2 != 0 ==> 返回 false)
5. 现在执行 for 循环的第三部分,使 i=6 和 j=0
6. 现在执行条件部分。返回 false 然后将 i 和 j 的值更改为 (i=9 and j=-1)

然后他们将值打印为 i=9 和 j=-1

如果它本来是预递增和预递减,那么它们将进入无限循环

于 2013-02-21T06:23:59.400 回答
1

您可以将代码更改为 while() 循环,如下所示:(我分别将 i, j 替换为 m, n)

int m = 3, n = 3;
while( m++ == n-- ){    //Initially m and n are 3
    //m becomes 4 due to ++
    //n becomes 2 due to --

    m = m + n;  //m becomes 6 
    while( m % n != 0){ // 6 % 2 is 0
        m = m + n;  // Not called
    }

    m = m + 2; // m becomes 8
    n = n - 2; // n becomes 0

   //Goes back to the while(m++ == n--) to check condition again. 
   //However ( 8++ == 0--) is false, so while loop is not called again.
   //but, the values of m and n change to 9 and -1 respectively. 
}

混合各种类型的循环可能会使调试变得有点复杂。

于 2013-02-21T06:24:48.803 回答