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

时间:2013-08-11 15:37:42

标签: c++ class for-loop

我有一个有4个考试成绩的课程。测试1 - 测试4。我想创建一个名为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;
        }

}

2 个答案:

答案 0 :(得分:2)

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

#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();

答案 1 :(得分:1)

你的意思是:

float mean(Cstudent section[], int n)
{
    int sum[NUMBEROFEXAMS];
    float mean[NUMBEROFEXAMS];
    for(int i = 0; i < NUMBEROFEXAMS; i+=4)
        for(int j = 0; j < n; j++){
            sum[i] += section[j].test1;
            sum[i+1] += section[j].test2;
            sum[i+2] += section[j].test3;
            sum[i+3] += section[j].test4;
        }

}