#include <iostream>
using namespace std;
int main (){
int row,
column = 0,
colCount = 3,
rowCount = 3;
//for loop
for (column; column < colCount; column++){
for(row = 0; row <= (rowCount - 1); row++){
cout << column << " " << row;
if(row < (rowCount - 1)){
cout << ", ";
}
}
cout << endl;
}
//while loop
while(column < colCount){
while(row < rowCount){
cout << column << " "<< row;
if(row < (rowCount - 1)){
cout << ", ";
}
row++;
}
cout << endl;
column += 1;
row = 0;
}
//do while loop
do{
do{
cout << column << " "<< row;
if(row < (rowCount - 1)){
cout << ", ";
}
row++;
}while(row < rowCount);
cout << endl;
column +=1;
row = 0;
}while(column < colCount);
}
当评论出2/3循环时,每个循环都会产生想要的输出。 它们似乎在一起运行,并增加了额外的输出。
0 0, 0 1, 0 2
1 0, 1 1, 1 2
2 0, 2 1, 2 2
3 3
0 0, 0 1, 0 2
1 0, 1 1, 1 2
2 0, 2 1, 2 2
0 0, 0 1, 0 2
1 0, 1 1, 1 2
2 0, 2 1, 2 2
0 0, 0 1, 0 2
1 0, 1 1, 1 2
2 0, 2 1, 2 2
如何从每个循环中获得输出?
答案 0 :(得分:1)
您可以按原样保留for
循环:
for (; column < colCount; column++){
for(row = 0; row <= (rowCount - 1); row++){
std::cout << column << " " << row;
if(row < (rowCount - 1))
std::cout << ", ";
}
std::cout << std::endl;
}
现在column
和row
在for-loop
上方获得3,这使得while loop
永远不会被执行。因此,您需要将它们都设为0
。
并且,第三个do-while
循环总是在任何条件检查之前执行,这就是为什么你得到3 3
无论如何,这是解决问题的方法。
#include <iostream>
int main ()
{
int row, column = 0, colCount = 3, rowCount = 3;
//for loop
for (column; column < colCount; column++){
for(row = 0; row <= (rowCount - 1); row++){
std::cout << column << " " << row;
if(row < (rowCount - 1))
std::cout << ", ";
}
std::cout << std::endl;
}
std::cout<<std::endl;
//while loop
column = 0;
row = 0;
while(column < rowCount){
while(row < rowCount){
std::cout << column << " "<< row;
if(row < (rowCount - 1))
std::cout << ", ";
row++;
}
std::cout << std::endl;
column += 1;
row = 0;
}
//do while loop
std::cout<<std::endl;
column = 0;
row = 0;
do{
do{
std::cout << column << " "<< row;
if(row < (rowCount - 1))
std::cout << ", ";
row++;
}while(row < rowCount);
std::cout << std::endl;
column +=1;
row = 0;
}while(column < colCount);
return 0;
}
答案 1 :(得分:0)
1)您应该在每个循环开始时将column
初始化为0
2)在while
和do
循环内,在进入内循环之前将row
初始化为0
最后的输出3 3
是由do-while
循环中的单个入口引起的。