Problem overview
This first version of the report card program works out one number: a student's average score over three tests. The starter code gives the scores as three int variables, test1, test2 and test3, holding 85, 92 and 78. You add a variable named average and print it after the text Average: .
The three scores add up to 255, and 255 divided by 3 is exactly 85, so the program prints:
Average: 85
The next version builds on this one.
Approach: add first, then divide
An average is the sum of the values divided by how many there are. In C++ you write that with two operators, and the order matters: the sum has to be complete before the division happens.
The lesson wants a whole number. When both sides of / are int, C++ does integer division: it keeps the whole part and throws away the remainder (it truncates toward zero). You don't need a cast or a rounding function. With the scores 90, 91 and 91 the sum is 272, and 272 / 3 gives 90, not 90.67. With double operands, 272 / 3.0 would print 90.6667, so the types decide which kind of division you get.
Step by step
- Declare
averageas anint. Its initial value is the sum of the three tests, in parentheses, divided by 3. Anintvariable matches the integer result of the division. - Print the result. Send the text
"Average: "tocout, thenaverage, thenendlto end the line. The lesson's tests read what the program prints, so a value that only sits in a variable isn't checked.
The solution in C++
int test1 = 85;
int test2 = 92;
int test3 = 78;
int average = (test1 + test2 + test3) / 3;
cout << "Average: " << average << endl;
The parentheses are the part that learners most often get wrong. Division binds tighter than addition, just as in arithmetic class, so without them test1 + test2 + test3 / 3 divides only test3. With the starter values that expression gives 203, because 78 / 3 is 26 and 85 + 92 + 26 is 203.
Dividing each score first and adding afterwards is also wrong. Each division drops its own remainder, so test1 / 3 + test2 / 3 + test3 / 3 gives 28 + 30 + 26 = 84, one less than the right answer of 85.
Edge cases and common mistakes
- Remainders are dropped, not rounded. 272 / 3 is 90, even though the exact average is closer to 91. Integer division always cuts, and for non-negative numbers that means rounding down.
- Negative results truncate toward zero.
-7 / 2is -3, not -4. This doesn't matter for test scores, but it surprises people who expect rounding down. - Misplaced parentheses. Check that the sum is inside them and the
/ 3is outside. - Wrong divisor. The 3 is the number of tests. If you add a fourth test, change it to 4.
- Missing line end. Without
endlthe output doesn't end with a newline.
Testing
Run the program with the starter values and compare the output with Average: 85. Then try changing the scores: with 90, 91 and 91 the program prints Average: 90, which shows that the remainder is dropped.
