Algorithm 为什么循环要比循环体多执行一次?

Algorithm 为什么循环要比循环体多执行一次?,algorithm,computer-science,Algorithm,Computer Science,算法教科书中的一段引文: 当for或while循环以通常的方式退出时(即,由于循环头中的测试),测试的执行次数比循环体多一次 因此,例如,以j=1到3的开头的for循环将不会执行3次,而是执行4次 问题:为什么这样的循环要执行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 l

算法教科书中的一段引文:

当for或while循环以通常的方式退出时(即,由于循环头中的测试),测试的执行次数比循环体多一次

因此,例如,以j=1到3的
开头的for循环将不会执行3次,而是执行4次

问题:为什么这样的循环要执行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。

我想你对书中的陈述感到困惑

当for或while循环以通常的方式退出时(即,由于循环头中的测试),测试的执行次数比循环体多一次

这意味着循环条件将比循环体多测试一次,因此通过您的示例:

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…循环的伪机器代码

// 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:
//int result=0;
//对于(int x=0;x<10;x++){
//结果+=x;
// }
MOV-edx,0//result=0
MOV-eax,0//x=0
.ForLoopLabel:
CMP-eax,10//FillFlags(x-10)
JGE.ForLoopFinishedLabel//如果x>=10,则转到ForLoopFinishedLabel
//对于loop的身体
添加edx,eax//result+=x
//身体末端
添加eax,1//x++
JMP.ForLoopLabel//转到ForLoopLabel
.ForLoopFinishedLabel:

这是真的吗,这本书是什么?请添加参考。您的推理是正确的,但您必须意识到,为了决定不执行,必须测试j=4。因此,“总是”有最后一个测试失败,这使得它比主体执行多出一个。“你还想要一块糖果?”“是的。”“好的,你还想要一块吗?”“是的。”“好的,还想要一块吗?”“不。”问了多少问题,你得到了多少糖果?