[英]Why can't I define a count variable outside of my loop in this function (C++)
This is a very basic question, I know, but I was solving the following simple exercise:这是一个非常基本的问题,我知道,但我正在解决以下简单的练习:
my2Darray is a two-dimensional array of doubles with nRows rows and nCols columns. my2Darray 是一个二维数组,包含 nRows 行和 nCols 列。 Write a function that sums all the elements in each column and returns them in an array called totalsByColumn.编写一个 function 对每一列中的所有元素求和,并将它们返回到一个名为 totalsByColumn 的数组中。 Write a second function that sums all the elements in each row, and returns them in an array called totalsByRow.编写第二个 function 对每一行中的所有元素求和,并将它们返回到一个名为 totalsByRow 的数组中。
My code works just fine now, but I was very curious as to why the following function wasn't working:我的代码现在工作得很好,但我很好奇为什么下面的 function 不起作用:
void colSum (int arrayArg[nRows][nCols]) {
static int sumofCols[nCols] = {};
int rowcount = 0;
for (int i = 0; i < nCols; i++) {
for ( ; rowcount < nRows; rowcount++) {
sumofCols[i] += arrayArg[rowcount][i];
}
cout << sumofCols[i] << endl;
}
}
Why is it that I can't create this rowcount
variable outside of my nested for
loops?为什么我不能在嵌套for
循环之外创建这个rowcount
变量? Only the first column of the two rows from the array I used as argument to the function was being summed into sumofCols[0]
, which led to sumofCols[1]
to equal 0. When I set rowcount
within the boundaries of either the first for
loop, or the second one, the iteration works just as intended.只有我用作 function 参数的数组中两行的第一列被汇总到sumofCols[0]
中,这导致sumofCols[1]
等于 0。当我将rowcount
设置在第一个的边界内for
循环或第二个循环,迭代按预期工作。
for (int rowcount = 0; rowcount < nRows; rowcount++)
This is the code I had to use.这是我必须使用的代码。
I just wanted to make sure I understand 100% of what I'm doing, as C++ can be quite confusing for a beginner like me.我只是想确保我 100% 了解我在做什么,因为 C++ 对于像我这样的初学者来说可能会很混乱。
Oh, and I did change this function to return an int*
value, as I'm basically assigning sumofCols
to another array, as the exercise demands.哦,我确实更改了这个 function 以返回一个int*
值,因为我基本上是根据练习的需要将sumofCols
分配给另一个数组。
Because after the first iteration rowCount will be equal to nRows.因为在第一次迭代之后 rowCount 将等于 nRows。 And for the 2nd iteration of the outerloop it doesn't re-initialize to 0 therefore the code inside this for (; rowcount < nRows; rowcount++)
loop doesn't work.对于外循环的第二次迭代,它不会重新初始化为 0,因此for (; rowcount < nRows; rowcount++)
循环中的代码不起作用。 You have to reset the value of rowCount to 0 after the iteration of the inner loop.在内部循环的迭代之后,您必须将 rowCount 的值重置为 0。 If you really want to declare the rowCount outside of the loop you can do the following,如果您真的想在循环之外声明 rowCount,您可以执行以下操作,
void colSum (int arrayArg[nRows][nCols]) {
static int sumofCols[nCols] = {};
int rowcount = 0;
for (int i = 0; i < nCols; i++) {
for ( ; rowcount < nRows; rowcount++) {
sumofCols[i] += arrayArg[rowcount][i];
}
cout << sumofCols[i] << endl;
rowCount = 0; // Here we are resetting the value to 0.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.