为什么循环比循环体多执行一次?
Why are loops executed one more time than the loop body?
引自算法教科书:
"When a for or while loop exits in the usual way (i.e., due to the test in the loop header), the test is executed one time more than the loop body."
因此,例如以for j=1 to 3
开头的for循环将执行4次而不是3次!
问题:为什么这样的循环会执行4次而不是3次?
根据我的推理:
When j = 1, the loop is executed.
When j = 2, the loop is executed.
When j = 3, the loop is executed.
When j = 4, the loop is NOT executed.
我数的是 3,不是 4。
我想你对书中的说法感到困惑
When a for or while loop exits in the usual way (i.e., due to the test in the loop header), the test is executed one time more than the loop body.
这意味着循环条件将比循环体多测试一次,因此根据您的示例:
for j = 1:3
j = 1, pass and looped
j = 2, pass and looped
j = 3, pass and looped
j = 4, failed and code executes as written
这是 for...loop
的伪机器代码
// int result = 0;
// for(int x = 0; x < 10; x++) {
// result += x;
// }
MOV edx, 0 // result = 0
MOV eax, 0 // x = 0
.ForLoopLabel:
CMP eax, 10 // FillFlags(x - 10)
JGE .ForLoopFinishedLabel // IF x >= 10 THEN GoTo ForLoopFinishedLabel
// for loop's body
ADD edx, eax // result += x
// end of body
ADD eax, 1 // x++
JMP .ForLoopLabel // GoTo ForLoopLabel
.ForLoopFinishedLabel:
引自算法教科书:
"When a for or while loop exits in the usual way (i.e., due to the test in the loop header), the test is executed one time more than the loop body."
因此,例如以for j=1 to 3
开头的for循环将执行4次而不是3次!
问题:为什么这样的循环会执行4次而不是3次?
根据我的推理:
When j = 1, the loop is executed.
When j = 2, the loop is executed.
When j = 3, the loop is executed.
When j = 4, the loop is NOT executed.
我数的是 3,不是 4。
我想你对书中的说法感到困惑
When a for or while loop exits in the usual way (i.e., due to the test in the loop header), the test is executed one time more than the loop body.
这意味着循环条件将比循环体多测试一次,因此根据您的示例:
for j = 1:3
j = 1, pass and looped
j = 2, pass and looped
j = 3, pass and looped
j = 4, failed and code executes as written
这是 for...loop
的伪机器代码// int result = 0;
// for(int x = 0; x < 10; x++) {
// result += x;
// }
MOV edx, 0 // result = 0
MOV eax, 0 // x = 0
.ForLoopLabel:
CMP eax, 10 // FillFlags(x - 10)
JGE .ForLoopFinishedLabel // IF x >= 10 THEN GoTo ForLoopFinishedLabel
// for loop's body
ADD edx, eax // result += x
// end of body
ADD eax, 1 // x++
JMP .ForLoopLabel // GoTo ForLoopLabel
.ForLoopFinishedLabel: