2016-02-19 197 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; ...; ...)。