2016-02-19 127 views
1

我需要幫助理解while循環之間的邏輯區別/ for循環,這裏的示例代碼:邏輯/ while循環

#include<iostream> 
using namespace std; 

int main(void) 
{ 
cout << "A multiplication table:" << endl 
     << " 1\t2\t3\t4\t5\t6\t7\t8\t9" << endl 
     << "" << endl; 
for(int c = 1; c < 10; c++) 
{ 
     cout << c << "| "; 
     for(int i = 1; i < 10; i++) 
     { 
     cout << i * c << '\t'; 
     } 
     cout << endl; 
} 
return 0; 
} 

我試圖重寫它作爲一個while循環,但結局缺少信息。

#include <iostream> 
using namespace std; 


int main() { 
    int i = 1; 
int c = 1; 
while (c< 10){ 
    cout << c <<"|"; 
    c++; 
    while (i< 10){ 
     cout << i * c << '\t'; 
     i++; 


    } 
    cout << endl; 
} 

cin.clear(); 
cin.ignore(); 
cin.get(); 

return 0; 
} 

有人建議我重置爲1將給出結果的其餘部分,我無法理解爲什麼while循環需要重置,而for循環沒有。

回答

1
for (i=0;i<n;i++) { 
    dosomething; 
} 

等同於:

i=0; 
while (i<n) { 
    dosomething; 
    i++; 
} 

在你的代碼的問題是,你不重置i 1在內部循環。 在循環內聲明int i=1而不是在c之外。

試試這個:

#include <iostream> 
using namespace std; 


int main() { 
int c = 1; 
while (c< 10){ 
    cout << c <<"|"; 
    c++; 
    int i=1; 
    while (i< 10){ 
     cout << i * c << '\t'; 
     i++; 


    } 
    cout << endl; 
} 

cin.clear(); 
cin.ignore(); 
cin.get(); 

return 0; 
} 
+0

這有助於噸,感謝您的幫助! – xanvier

1

你將不得不設置i = 1到獲得這兩個例子您的預期行爲。在for循環中,這已經被處理了,因爲在for循環的頭部有一個for(int i = 1; ...; ...)。