Geo*_*rge 4 algorithm computer-science
引用自算法教科书:
“当 for 或 while 循环以通常的方式退出时(即,由于循环头中的测试),测试比循环体多执行一次。”
因此,例如,以 开头的 for 循环for j=1 to 3将不会执行 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.
Run Code Online (Sandbox Code Playgroud)
我数 3,而不是 4。
小智 5
我想你对书中的陈述感到困惑
当 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
Run Code Online (Sandbox Code Playgroud)