关于嵌套的for循环
Regarding nested for loops
我有一个赋值使用嵌套的for循环打印出5行3列二维数组的索引,而不使用数组。
#include <iostream>
using namespace std;
int main()
{
int row;
int column;
cout << "Counting with nested loops: indices of row, column" << endl << endl;
for (row = 1; row <= 5; row++)
{
for (column = 1; column <= 3; column++)
{
}
cout << row << "," << column << "t" << row << "," << column << "t" << row << "," << column << "t" << endl;
}
cout << "nnn" << endl;
return 0;
}
这是我到目前为止的代码。我的目标是打印
1,1,1,2,1,3
2、1、2、2、3
等等。当我运行程序时,它打印
1,4 1,4 1,4
2,4 2,4 2,4
所以行部分是正确的。谁能帮我找出我的错误是什么?
你只需要调用一次print,但是在内部循环中像这样:
for (row = 1; row <= 5; row++){
for (column = 1; column <= 3; column++){
std::cout << row << "," << column << "t";
}
std::cout << std::endl;
}
这是你必须写的代码:
int main() {
int row;
int column;
cout << "Counting with nested loops: indices of row, column" << endl << endl;
for (row = 1; row <= 5; row++) {
for (column = 1; column <= 3; column++) {
cout << row << "," << column << "t";
}
cout << endl;
}
cout << "nnn" << endl;
return 0;
}
这是因为你必须在第二个循环里面打印而不是在外面。
其他人已经回答了这个问题,但我想添加一些建议,给将来考虑的事情。
首先在你引入循环变量的地方,例如int row;
,你还没有初始化它们,只需要在for
循环中声明它们。然后它们将不会在for
循环之外可见,这将避免在循环完成后(通过cout
)打印的错误。
也值得考虑循环计数器。通常从0开始。此外,数组的下标将从0开始,一直到n-1。所以你应该考虑打印0,1,…而不是1,2,…如果你想用它来遍历数组,
#include <iostream>
using namespace std;
int main()
{
cout << "Counting with nested loops: indices of row, column" << endl << endl;
for (int row = 0; row < 5; row++) //<--- note start at 0 and stop BEFORE n
{
for (int column = 0; column < 3; column++) //<--- ditto
{
cout << row << "," << column << "t";
}
//cout << row << "," << column << "t"
<< row << "," << column << "t"
<< row << "," << column << "t" << endl;
// Now compile error
// And clearly was going to just give the same value
// for row and column over and over
cout << 'n';//added to break each row in the output
}
cout << "nnn" << endl;
return 0;
}
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么我的for循环不能正确获取argv
- 在基于范围的for循环中使用结构化绑定声明
- 通过for循环使用用户输入填充列表
- 使用for循环检查数组中的重复项
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 正在使用for循环创建QScatterSerie
- Python中的for循环与C++有何不同
- 在更改for循环的第三部分后,未使用for循环结果
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- 如何用for循环在c++中生成单词三角形
- 如何在for循环中包含两个索引值的测试条件
- 带有多个独立参数的C++For循环
- 为什么我的程序在for循环中k=0时返回垃圾值
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- C++-For循环未执行
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- C++ 无法在字符数组中使用 for 循环打印字母模式