如何在for循环中定义多维数组的一部分

How to define part of multi-dimensional array inside of a for loop?

本文关键字:数组 一部分 定义 for 循环      更新时间:2023-10-16

我是数组的新手,一直在尝试做以下事情:

a) generate a 12x12 matrix of random numbers
b) output the matrix
c) compute and output the sum of the rows
d) compute and output the sum of the columns

到目前为止,我已经能够做a, b, c和d的一部分。

我的代码是:
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
const int M = 12;
const int N = 12;
int myArray[M][N] = {0};
int rowSum[M] = {0};
int colSum[N] = {0};

void generateArray();
void sumRowsAndColumns();
int main()
{
    generateArray();
    sumRowsAndColumns();
    return 0;
}
void generateArray()
{
    // set the seed
    unsigned setSeed = 1023;
    srand(setSeed);
    // generate the matrix using pseudo-random numbers
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            myArray[i][j] = rand() % 100;
            // outputs the raw matrix (in case we need to see it)
            cout << left << setw(4) << myArray[i][j] << " ";
        }
        cout << endl;
    }
    cout << endl << endl;
}
void sumRowsAndColumns()
{
    cout << endl;
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; ++j)
        {
            rowSum[i] += myArray[i][j];
            colSum[j] += myArray[i][j];
        }
        cout << left << setw(6) << rowSum[i] << endl;
        cout << left << setw(6) << colSum[j] << endl;  // the error indicates the the 'j' is undefined
    }
}

:

cout << left << setw(6) << colSum[j] << endl; 

我得到错误:

"j is undefined"

令人困惑的是,当我在Visual Studio中将鼠标悬停在"colSum"上时,我可以"看到"结果。我只是输出有问题。

谁能提供任何指导,在如何定义"j"(即使它看起来像它被定义)?

谢谢,瑞安

这个错误是不言自明的:打印输出发生在嵌套循环之外,所以j不再在作用域中。当变量在复合语句的头部分定义时,例如ifforwhile,该变量的作用域(即可以使用该变量的地方)以相应的控制语句结束。

你可以改变你的代码使用i索引rowSumcolSum。您还需要在嵌套循环中切换+=操作中的索引,以赋予ij适当的含义:

for (int i = 0; i < M; i++)
{
    for (int j = 0; j < N; ++j)
    {
        // For rowSum, i means the row and j means the column
        rowSum[i] += myArray[i][j];
        // For colSum, it is the other way around
        colSum[i] += myArray[j][i];
    }
    // In both cases i represents the current sum:
    // row sum for the rowSum[] array, and column sum for colSum[] array
    cout << left << setw(6) << rowSum[i] << endl;
    cout << left << setw(6) << colSum[i] << endl;
}

在循环内定义j,并在循环外引用它。但是一旦你离开循环,j就超出了作用域