C ++代码,使用户在多维数组中输入行和列

c++ code which makes the user input the rows and columns in a multidimensional array

本文关键字:数组 输入 代码 用户      更新时间:2023-10-16

im 制作一个程序,显示一个乘法表,用户提示行数和列数,该程序显示表但列数和行数应该相同,如果我输入不同的数字,就会发生错误。

#include <iostream>
using namespace std;
int main()
{
    int r,c;
    cout<<"How many rows?: ";
    cin>>r;
    cout<<"How many Columns?: ";
    cin>>c;
    int table[r][c];
    //assigns each element
    for (int i = 1; i <= r; i++)
    {
        for (int j = 1; j <= c; j++)
        {
            table[i][j] = i * j;
        }
    }
    //prints the table
    for (int i = 1; i <= r; i++)
    {
        for (int j = 1; j <= c; j++)
        {
            cout << table[i][j] << 't';
        }
    }
    system("pause");
    return 0;
}

数组从索引0开始,如果数组大小r arr[r]则无法访问。所以你需要做:

for (int i = 0; i < r; i++)
    {
        for (int j = 0; j < c; j++)
        {
            table[i][j] = i * j;
        }
    }
    //prints the table
    for (int i = 0; i < r; i++)
    {
        for (int j = 0; j < c; j++)
        {
            cout << table[i][j] << 't';
        }
    }
嗨,

就像乔纳森波特说数组在 C/C++ 中从 0 开始。加:

int r,c;
cout<<"How many rows?: ";
cin>>r;
cout<<"How many Columns?: ";
cin>>c;
int table[r][c];

这是一个非常糟糕的做法,你应该避免。实际上,您正在使用非静态变量创建表。

这个问题在这里已经回答了