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, a for (int score : scores) loop is enough, because you only need the scores.
A new function, average(), will compute it. It gets the vector as a const std::vector<int>&, 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 scores.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
Above printResults(), write a function double average(const std::vector<int>& scores) that adds up all the elements of scores and returns the sum divided by their number.
At the end of printResults(), after the loop (not inside it), print the average computed by average(). A new line appears under the students' results:
Average score: 33.8If you see 33, you're adding up in an int variable. If you see 8.4, the return is inside the loop.
Start programming for free
3/7