C++ 和数组中的嵌套循环

Nested loops in c++ and arrays

本文关键字:嵌套循环 数组 C++      更新时间:2023-10-16

我正在用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++,该值确实会递增)。