Class Average
The teacher wants to know how the test went overall: how many points the students got on average. The average is the sum of the scores divided by the number of students. The sum is the pattern from the lesson on loops: a variable that starts at 0, and a loop that adds each value to it. Here, the loop goes through the students as const references, as in printResults(), and adds each student.score.
A new function, average(), will compute it. It gets the vector as a const std::vector<Student>&, just like printResults(): without a copy, and only for reading. It returns a decimal number, so its type is double.
Watch out for integer division. When you divide a whole number by a whole number, C++ throws away the remainder, and the result is a whole number again: 7 / 2 is 3. A sum stored in an int variable and divided by students.size() would give 33 instead of 33.8. You get a decimal result when at least one of the numbers is a decimal (7.0 / 2 is 3.5). The easiest way is to add the values up in a double variable right away:
std::vector<int> temperatures = {18, 21, 23, 19};
double sum = 0;
for (int t : temperatures) {
sum += t;
}
std::cout << "Average temperature: " << sum / temperatures.size() << std::endl;Average temperature: 20.25One more trap: return belongs after the loop. Inside the loop, it would end the function in the very first pass, and the average would be computed from the first student's score only.
Instructions
- 1
Between
grade()andprintResults(), write a functiondouble average(const std::vector<Student>& students)that adds up the scores of all the students and returns the sum divided by their number. - 2
At the end of
printResults(), after the loop (not inside it), print the average computed byaverage(). A new line appears under the students' results:Average score: 33.8If you see
33, you're adding up in anintvariable. If you see8.4, thereturnis inside the loop.