我如何使用嵌套的for循环为二维数组?(C++)[关闭]

moiiocjp  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(76)

**已关闭。**此问题为not reproducible or was caused by typos。目前不接受回答。

这个问题是由错字或无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
5天前关闭。
Improve this question

#include <iostream>
#include <iomanip>
   
using namespace std;

int main()
{
    const int NUM_ROWS = 5;
    const int NUM_COLS = 10;
    int array[NUM_ROWS][NUM_COLS]{};
    cout << "Array contents:" << endl;
    for (int row = 0;row<NUM_ROWS;row++)
    {
        for (int col=0;col<NUM_COLS;col++)
        { 
            int array[row][col] = rand () % 200;
            cout << array[row][col] << setw(2);
        }
    } 
}

的一个字符串
`我想通过使用5行和10列输入一个0-199之间的随机数(总共留下50个随机数值),但我的ide将int值:row和col注册为常规变量,我认为可以调整数组的维度。

xqnpmsa8

xqnpmsa81#

不使用“C”风格的数组,看看C++的数组(和基于范围的循环)

#include <array>
#include <random>
#include <iostream>

//using namespace std; // no do not us this

int main()
{
    // C++ random generation
    std::random_device entropy_source{};
    std::mt19937 random_generator{ entropy_source() };
    std::uniform_int_distribution<int> distribution{ 0,199 };

    //C++ 2D array 
    // with C++ arrays you can pass them around like objects
    // and return them from functions (instead of using raw pointers 
    // and running into "C" style pointer decay and memory allocation unclarities)
    std::array<std::array<int, 10>, 5> values;

    //C++ arrays keep track of their own size of use later
    std::cout << "number of rows = " << values.size() <<"\n";

    // prefer range based for loops, they cannot go out of bounds
    for (auto& row : values)
    {
        for (auto& value : row)
        {
            value = distribution(random_generator);
            std::cout << value << " ";
        }
        std::cout << "\n";
    }

    return 0;
}

字符串

oogrdqng

oogrdqng2#

这条线

int array[row][col] = rand () % 200;

字符串
int是无效的语法。前导int使其成为新局部变量array的声明(隐藏了main()第三行的外部声明),但初始化器rand() % 200对于初始化数组无效,因此您将获得编译器错误。
删除前面的int,将此声明转换为赋值,程序将编译:

array[row][col] = rand () % 200;

相关问题