c++ - 在一个函数中使用类的每个成员来计算平均值

标签 c++ class for-loop

我的类(class)有 4 个考试成绩。测试 1 - 测试 4。我想创建一个名为 mean 的函数,它将计算类(class)中每门考试的平均值并将其存储在 mean 数组中。但我似乎无法通过一个循环来完成此操作:

class Cstudent
{
public:
    string firstName, lastName;
    int test1, test2, test3, test4;
    float average;
};

/* Here is the problem, the next time i go through the loop, i want to store the sum of
test2 in to sum[1] after already storing the total in to sum[0] for test 1 */

float mean(Cstudent section[], int n)
{
    int sum[NUMBEROFEXAMS];
    float mean[NUMBEROFEXAMS];
    for(int i = 0; i < NUMBEROFEXAMS; i++)
        for(int j = 0; j < n; j++){
            sum[i] += section[j].test1;
        }

}

最佳答案

将分数存储在数组中会更容易:

#include <array>

class Student
{
public:
    string firstName, lastName;
    std::array<int, 4> test;
    float average;
};

然后你可以很容易地得到平均值:

#include <algorithm> // for std::accumulate

Student s = ....;
...
float avg = std::accumulate(s.test.begin(), s.test.end(), 1.0)/s.test.size();

关于c++ - 在一个函数中使用类的每个成员来计算平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18173596/

相关文章:

java - 在ant中定义一个变量列表,可以在for循环中使用

c++ - 将 C++ 用于性能密集型应用程序?

c++ - 未找到 BFD 库

C++ 明格 : Two objects of the same class are changing the data across eachother

c++ - 使用另一个类的函数指针

linux - Bash:一次有两个 for 循环?

c - C 中 for 和 while 循环的区别?

C++:在派生类构造函数中调用基类赋值运算符的形式不正确?

c++ - 实现自定义迭代器以与 std::find 一起工作

c++ - 条件 if 中类成员的范围