2015-08-25 104 views
3

從算法教科書引述:爲什麼循環會比循環體多執行一次?

「當一個爲或當以通常的方式退出循環(即,由於在循環頭的測試),測試被執行的一個時間比循環更身體。」

因此,例如,以for j=1 to 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

+0

是真的,這本書是什麼?請加上參考.. – Balaji

+2

你的推理是正確的,但你必須認識到,爲了決定不執行j = 4必須經過測試。因此,「總是」最後一次測試失敗,使得它比身體執行更重要。 「你想要一顆糖果?」 「是。」 「好的,你還想要一個?」 「是。」 「好的,還有一個?」 「沒有。」問了幾個問題,你有多少糖果? –

回答

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 
1

下面是一對......循環

// 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: 
僞機器碼