-7 c#
int x = 1;
while (x++ < 5)
{
if ((x % 2) == 0)
x += 2;
}
Run Code Online (Sandbox Code Playgroud)
问题是以下循环将执行多少次?我可以看到第1个x等于1,第2个x等于2,第3个x等于4,我认为它会执行3次,但为什么答案是2次?
正如你所说的那样,while循环的主体确实会执行两次,而不是三次.
这就是原因.
我将展开循环,以便我们可以看到会发生什么.
int x = 1; // x is now 1
while (x++ < 5) // read the current value of x, which is 1
// then increase x by 1, giving it the value 2
// then compare the value we read (1) with 5
// since 1 < 5, we will execute the body of
// the while loop
{
if (x % 2 == 0) // x is equal to 2, "2 % 2" is equal to 0
// so execute the body of the if-statement
x += 2; // increase x by 2, giving it the value 4
}
// while (x++ < 5) // read the current value of x, which is 4
// then increase x by 1, giving it the value 5
// then compare the value we read (4) with 5
// since 4 < 5, we will execute the body of
// the while loop
{
if (x % 2 == 0) // x is equal to 5, "5 % 2" is NOT equal to 0
// so do not execute the body of the if-statement
}
// while (x++ < 5) // read the current value of x, which is 5
// then increase x by 1, giving it the value 6
// then compare the value we read (5) with 5
// since 5 < 5 is not true, we will NOT
// execute the body of the while loop
Run Code Online (Sandbox Code Playgroud)
我们已经完成了
最终价值x是6.
所以答案是,正如你所说,while循环的主体执行两次.
| 归档时间: |
|
| 查看次数: |
182 次 |
| 最近记录: |