2013-05-30 146 views
0

這是一個非常特殊的情況,但我是C++的新手,並且不理解我爲項目euler網站編寫的這個程序的輸出。循環中的C++範圍

int x = 999; 
int y = 999; 
string result; 

while (x > 320) 
    { 
    while(y > 320) 
     { 
     int inttoconvert = (x*y); 
     cout<<inttoconvert<<"<-----This is product"<<endl; 
     string result; 
     ostringstream convert; 
     convert << inttoconvert; 
     result = convert.str(); 

     if (result[0] == result[5] && result[1] == result[4] && result[2] == result[3]) 
      { 
      cout<<"The largest palindrome of 2 3-digit numbers is "<<result<<endl; 
      y = 0; 
      x = 0; 
      } 
     else 
      { 
      cout<<y<<endl; 
      y--; 
      } 
     }//end while 
    cout<<"this is x---->"<<x<<endl; 
    x--; 

    }//end while 

輸出顯示X減Y已遞減到321只後,但隨後一再遞減,程序不進入第二而再次循環。

我開始變得疑神疑鬼關於視覺表達

+1

你期望發生的?一旦'y <= 320','y'永遠不會再次增加,所以代碼不會有任何理由多次進入內部循環。 – Mankarse

+0

這不是一個範圍界定問題,而是一個邏輯/算法問題。 – squiguy

+0

錯誤在於你的代碼,而不是編譯器。 –

回答

1

你永遠不會重置Y,我相信這就是爲什麼你再次有問題

2

程序不會進入第二個while循環,因爲嵌套循環全部共享相同的範圍。在退出第二個while循環後,y不會再次被重置。所以一旦y不能滿足內環的條件,它不會進入它,它會跳過它,直接進入遞減x

0

進入循環。在(y> 320)循環後,y等於320. 退出(y大於320)循環。 x減少到998. 再次檢查(x> 320)條件。 這是真的,所以它試圖再次執行(y> 320)循環。 y仍然等於320,所以它不能再次進入該循環。 因此,它將繼續跳過該循環並遞減x。

2

您應該在x循環的開始處初始化y,而不是在兩個循環之外。

int x = 999; 
string result; 

while (x > 320) 
    { 
    int y = 999; 
    while(y > 320) 

您還可以使用for循環,而不是while

for (int x = 999; x > 320; x--) { 
    for (int y = 999; y > 320; y--) { 
    ... 
    } 
}