C++ 和数组中的嵌套循环
Nested loops in c++ and arrays
我正在用c ++编写这个程序,无法确定我做错了什么。这个嵌套循环应该打印一个包含行和列的矩阵,并且由于某种原因,它在要求用户输入时卡在第 0 行和第 0 列。提前谢谢。
#include <iostream>
using namespace std;
int main ()
{
//program to print the input values in rows and columns of two dimensional array in revserse roder using loop
//decalre the vraibles and array
int array [3][3],rows,cols,maxrows = 3,maxcols = 3;
//use for loop to intiiate the array and input values from users
for (rows = 0; rows < maxrows;rows = rows++ )
{
for (cols = 0; cols < maxcols;cols = cols++ )
{
cout << " Enter the value for array location : " << " [ " << rows << " , " << cols << " ] " ;
cin >> array [rows][cols] ;
}
}
//display the values entered in array starting with bottom row first and then the rest
for ( rows = 0 ; rows < maxrows ; rows ++ )
{
for ( cols = 0 ; cols < maxcols ; cols ++ )
{
cout << " The values that were entered in this array starting with bottom row are " << array [rows][cols] ;
}
}
}
你已经有了答案,但我想我应该指出变量声明的风格。即int array [3][3],rows,cols,maxrows = 3,maxcols = 3;
这很糟糕,因为它的可读性不是很强。行变量和列变量的类型在最严格的意义上是不正确的,请参阅为什么size_t将其用作数组索引时更好。此外,可以说明为什么你应该赞成前递增而不是后递增,除非你有充分的理由不这样做(++i 而不是 i++),尽管在这种特殊情况下这并不重要,因为运算符没有重载。此外,适当地使用常量可以使代码更具可读性并消除某些类型的错误。最后,尽快给你的变量一个合理的值,以消除未定义的行为。
#include <iostream>
using namespace std;
int main ()
{
//program to print the input values in rows and columns of two dimensional array in revserse roder using loop
//decalre the vraibles and array
int array [3][3] = {};
const size_t maxrows = 3,
const size_t maxcols = 3;
//use for loop to intiiate the array and input values from users
for (size_t rows = 0; rows < maxrows; ++rows )
{
for (size_t cols = 0; cols < maxcols; ++cols )
{
cout << " Enter the value for array location : " << " [ " << rows << " , " << cols << " ] " ;
cin >> array [rows][cols] ;
}
}
//display the values entered in array starting with bottom row first and then the rest
for ( size_t rows = 0; rows < maxrows ; ++rows)
{
for ( size_t cols = 0; cols < maxcols ; ++cols)
{
cout << " The values that were entered in this array starting with bottom row are " << array [rows][cols] ;
}
}
}
评论暗示了问题,但没有明确说明:
rows = rows++
不明确,因为在获取值后右侧递增,然后将其分配给左侧。为 g++ 启用适当的警告后,它说
foo.c:26: warning: operation on ‘rows’ may be undefined
实际上,它说一些编译器可能会给出不同的结果,例如使其与
rows = rows
如果它这样做,将导致无限循环。 (顺便说一下,对于 g++,该值确实会递增)。
相关文章:
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 了解嵌套循环打印星号图案
- 无法掌握嵌套循环的写作技巧
- 在 c++ 中实现嵌套循环的更短方法吗?
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- 在 glsl opengl 中将嵌套结构数组作为统一传递
- 使用嵌套函数数组是个好主意吗?
- 具有动态数组分配的OpenMP嵌套循环
- 按升序对数组进行排序嵌套循环问题
- 用于在一维数组上嵌套循环操作的正确 openmp 指令
- C 从嵌套循环中的文件中读取,并将值分配给二维数组
- 如何初始化嵌套结构数组
- C++ 和数组中的嵌套循环
- 二维数组和嵌套循环
- C++嵌套循环/动态数组E
- 嵌套循环中的 OpenMP 数组索引
- 将数组成员与嵌套循环进行比较,计算满足条件(if)的次数
- 嵌套循环和模数
- 初始化嵌套结构数组
- 在数组链表中使用一个嵌套循环从一个位置迭代到另一个位置