我正在尝试使用 C++ 中的 2D 数组进行试验,我正在开发一个 4x4 2D 数组的项目,该数组包含许多学生成绩,但它是通过文本文件部分填充的。 4 列中只有 3 列被填充。我想用每列前几行的平均成绩填充最后一列。
问题是我不知道如何填写最后一列。
这是我计算平均值的代码。
const int SIZE = 4;
const int ROWS = 4;
const int COLS = 4;
int total = 0;
for (int i = 0; i < ROWS; i++)
{
total = 0;
for (int j = 0; j < COLS - 1; j++)
{
total += studentGrades[i][j];
average = total / (COLS - 1);
studentGrades[0][3] = average;
studentGrades[1][3] = average;
studentGrades[2][3] = average;
studentGrades[3][3] = average;
}
}
我似乎接近了,因为我得到了很好的结果,但最后一列没有显示正确的值,我觉得有一种更有效的方法来填充最后一列,而不是手动插入到每个索引中。
最佳答案
您每次都将最后计算的平均值分配给所有行。这意味着最后您将得到所有 4 列中第 4 行的平均值。还可以考虑将变量(studentGrades
和 total
)更改为浮点类型以获得更高的准确性。
const int SIZE = 4;
const int ROWS = 4;
const int COLS = 4;
for (int i = 0; i < ROWS; i++)
{
int total = 0;
for (int j = 0; j < COLS - 1; j++)
total += studentGrades[i][j];
studentGrades[i][COLS - 1] = total / (COLS - 1);
}
您还可以使用标准库:
#include <numeric>
// ...
constexpr int Rows = 4, Cols = 4, NGrades = Cols - 1;
for (int i = 0; i < Rows; i++)
studentGrades[i][NGrades] = std::accumulate(studentGrades[i], studentGrades[i] + NGrades, 0) / NGrades;
在我的第一个解决方案中,考虑使用浮点类型。要启用浮点运算,请将 std::accumulate
的 0
更改为 0.0
或 0.0f
。
Here是对 std::accumulate
的解释。
关于C++用平均值填充部分填充的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54280561/