如何在for循环中定义多维数组的一部分
How to define part of multi-dimensional array inside of a for loop?
我是数组的新手,一直在尝试做以下事情:
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
不再在作用域中。当变量在复合语句的头部分定义时,例如if
、for
或while
,该变量的作用域(即可以使用该变量的地方)以相应的控制语句结束。
你可以改变你的代码使用i
索引rowSum
和colSum
。您还需要在嵌套循环中切换+=
操作中的索引,以赋予i
和j
适当的含义:
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
就超出了作用域
相关文章:
- 在 MPI 中共享数组的一部分
- 将constexpr字节数组与缓冲区的一部分(指向数据的指针)进行比较
- 需要从字符串数组的一部分访问元素
- 如何在C++中创建 2d 数组,其中一部分包含循环计数器,另一部分包含数字列表?
- 如何反转数组的一部分?
- 如何在数组的一部分中查找特定值的第一个元素
- 如何在C++中比较数组中字符串的一部分的字符串
- 将字符数组的一部分提取为 char*
- 字符数组仅占用字符串的一部分
- 不允许删除数组的一部分,为什么
- 删除动态数组的一部分
- 如何翻转数组的一部分
- 发送字节数组的一部分
- for循环不包括需要包含数组的一部分
- C++将字符数组的一部分复制到另一个字符数组
- 如何将数组的一部分从 int 转换为浮点数并将值设置为另外两个数组
- 复制存储在内存映射文件中的数组的一部分
- 如何将此INT数组的一部分复制到C 中的另一个数组
- 有条件地确定字符串是否是数组的一部分
- 通过指向函数的指针循环传递数组的一部分