C++用平均值填充部分填充的二维数组

标签 c++ arrays

我正在尝试使用 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 行的平均值。还可以考虑将变量(studentGradestotal)更改为浮点类型以获得更高的准确性。

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::accumulate0 更改为 0.00.0f

Here是对 std::accumulate 的解释。

关于C++用平均值填充部分填充的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54280561/

相关文章:

arrays - 无法将 Array<Codable> 转换为 Codable

c++ - 为什么我的函数不返回 float ?

c# - 如何从列表数组(linq 列表)C# 中的所有元素调用方法

c - 将数组传递给函数以进行内存分配

objective-c - let/var 如何解决可变性?

c++ - 使用指向彼此的指针初始化 const struct 实例

c++ - std::integral_constant 背后的原因是什么?

c++ - Uncrustify 折叠多行函数调用

c++ - 使用 C++ 查找第 1500000 个斐波那契数

ios - 如何使用 NSMutableArray 填充 TableView