2017-03-18 147 views
0

我有這個簡單的程序相對於計算晶粒的數目,以正方形:while循環終止重寫?

#include "library/std_lib_facilities.h" 

/*There is an old story that the emperor wanted to thank the inventor of the game of chess and asked the inventor to name 
his reward. The inventor asked for one grain of rice for the first square, 2 for the second, 4 for the third, and so on, 
doubling for each of the 64 squares. That may sound modest, but there wasn’t that much rice in the empire! Write a 
program to calculate how many squares are required to give the inventor at least 1000 grains of rice, at least 1,000,000 
grains, and at least 1,000,000,000 grains.*/ 

int main() 
{ 
    int grains = 1; 
    int squares = 1; 

    while(grains < 1000) { 
     squares++; 
     grains *=2; 
     cout << grains << " rice grains for " << squares << " squares" << '\n'; 
    } 
    return 0; 
} 

環路打印每次循環後的晶粒和方形。這是在終端的輸出:

2 rice grains for 2 squares 
4 rice grains for 3 squares 
8 rice grains for 4 squares 
16 rice grains for 5 squares 
32 rice grains for 6 squares 
64 rice grains for 7 squares 
128 rice grains for 8 squares 
256 rice grains for 9 squares 
512 rice grains for 10 squares 
1024 rice grains for 11 squares 

正如你可以看到,循環終止小於被設定在grain < 1000終止條件越大。

我對結果沒有任何問題,我只想知道爲什麼循環超過終止標準,爲什麼它不停止在512粒?是因爲循環體中的正方形的迭代?

+2

終止條件時,纔會進行測試時,執行涉及到循環的開始 - 不要在循環 –

回答

2

因爲

while(grains < 1000) { //when grain value is 512, which is true. 
     squares++; 
     grains *=2; //become 1024 
     cout << grains << " rice grains for " << squares << " squares" << '\n'; 
    } 

相反,你可以改變你,而條件while(squares < 10)

int grains = 2; 
int squares = 2; 
while(grains < 1000) { //when grain value is 1024, which is false. 
      cout << grains << " rice grains for " << squares << " squares" << '\n'; 
      grains *=2; 
      squares++; 

     } 
+0

的每一個陳述後謝謝。現在更清楚了。我喜歡第一個例子,它更好地解釋了循環是如何工作的。 –

+0

然後你可以接受我想要的答案 – Ravi

+0

,但它給了我一個時間限制。無法接受在某些會議記錄等答案。 –