繁体   English   中英

二维数组填充随机数和输出索引 C++

[英]2D Array fill with random numbers and output index c++

我试图用 0 - 100 的随机数填充二维数组;

另外,我试图输出行的索引以输出行的单元格内的随机值。

我需要的帮助是显示此输出:

样品运行

The sum of row0 elements {41 + 67 + 34 + 0 + 69} is 211
The sum of row1 elements {24 + 78 + 58 + 62 + 64} is 286
The sum of row2 elements {5 + 45 + 81 + 27 + 61} is 219
The sum of row3 elements {91 + 95 + 42 + 27 + 36} is 291
The sum of row4 elements {91 + 4 + 2 + 53 + 92} is 242

检查我的代码:

#include <iostream>
#include <ctime>

int const row = 5;
int const col = 5;

void input (int [][col]);
void output(int [][col]);

using namespace std;

int main()
{
    srand(time(0));

    int array[row][col] = { 0 };

    input (array);
    output(array);

    system("pause");
    return 0;
}

void input(int array [row][col])
{

    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
        {
            array[i][j] = rand() % (100 - 1 + 1) + 1;
        }
    }
}

void output(int array[row][col])
{
    int sum;

for (int i = 0; i < row; i++)
{
    sum = 0;

    cout << "The sum of row" << i << " elements is {" << array[i][0];

    for (int j = 1; j < col; j++)
    {
        sum += array[i][j];
        cout << " + " << array[i][j];
    }
    cout << "} is " << sum << endl;
}

}

用这个替换 output() 函数

void output(int array[row][col])
{
    int sum;

    for (int i = 0; i < row; i++)
    {
        sum = 0;

        cout << "The sum of row" << i << " elements {" << array[i][0];
        for (int j = 1; j < col; j++)
        {
            sum += array[i][j];
            cout << " + " << array[i][j];
        }
        cout << "} is " << sum << endl;
    }

}

这会进行求和,因此摆脱了int total变量。 int indexi也没有使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM