摘自算法教科书的一段话:
“当 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.
我数了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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)