0

私は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;
        }

}
4

2 に答える 2

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();
于 2013-08-11T15:40:06.567 に答える