为什么循环比循环主体多执行一次? [英] Why are loops executed one more time than the loop body?

查看:107
本文介绍了为什么循环比循环主体多执行一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

算法教科书中的引言:


当for或while循环以通常方式退出时(即,由于测试在循环标题中执行),比循环主体多执行一次测试。

"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."

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

So, for example, a for loop that begins with for j=1 to 3 will be executed not 3 times, but 4 times!

问题:为什么这样的循环执行4次而不是3次?

Question: Why would such a loop be executed 4 times and not 3 times?

根据我的推理:

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。

推荐答案

我认为您对书中的陈述感到困惑

I think you are confused about what the statement in the book states


当for或虽然循环以通常的方式退出(即,由于循环头中的测试),所以测试比循环主体执行的时间多一遍。

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.

这意味着循环条件的测试时间将比循环体多一倍,因此,以您的示例为例:

This means that the loop condition will be tested one more time than the loop body therefore by your example:

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

这篇关于为什么循环比循环主体多执行一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆