Problem overview
Version 2 of the report card computes a weighted final score. Three marks count for different shares of the result: homework is worth 20%, midterm 30% and finalExam 50%. The starter code holds the marks 90, 82 and 88, and the program prints Score: followed by the result.
Each weighted part is rounded down before the parts are added: 90 × 20 / 100 is 18, 82 × 30 / 100 is 24 (the exact value is 24.6) and 88 × 50 / 100 is 44. The sum is 86:
Score: 86
Version 1 averaged three tests with equal weight. This version gives each mark its own weight.
Approach: mark times weight, divided by 100
A percentage is a fraction out of 100, so 20% of a mark is the mark times 20, divided by 100. Because all three variables are int, each division drops its remainder, which is exactly the "round down each part" rule.
The order inside each part matters: multiply first, divide last. If you write 20 / 100 on its own, both operands are integers and the result is 0, so the whole part becomes 0. With homework * (20 / 100) the program gives 0 for the homework part, whatever the mark is. Writing homework * 20 / 100 multiplies first (* and / have the same priority and go left to right), so the multiplication is done before the division.
Step by step
- Declare
scoreas anintand build it from three parts joined by+. - Write each part as mark × weight / 100:
homework * 20 / 100, then the same shape formidtermwith 30 andfinalExamwith 50. Note the third variable's name:finalExam, notfinal. - Print the score with
cout, the text"Score: ", the variable andendl.
The weights 20, 30 and 50 add up to 100, so a student with a mark of 100 everywhere gets a score of 100.
The solution in C++
int homework = 90;
int midterm = 82;
int finalExam = 88;
int score = homework * 20 / 100 + midterm * 30 / 100 + finalExam * 50 / 100;
cout << "Score: " << score << endl;
Each part is truncated on its own, and that can change the total. With the marks 95, 85 and 75 the parts are 19, 25 and 37, and the program prints 81. If you added the products first and divided once, (95 * 20 + 85 * 30 + 75 * 50) / 100, you would get 82, because the remainders would be combined instead of dropped one by one. The lesson's rule is to round each part, so keep the three divisions separate.
Edge cases and common mistakes
- Dividing the weight alone.
20 / 100is 0 in integer arithmetic. Multiply the mark first. - Using decimals by habit.
0.2 * homeworkproduces adouble, and decimal fractions like 0.2 can't be stored exactly in binary. The lesson stays with whole numbers: mark times weight, divided by 100. - Wrong variable name. The third mark is
finalExam, as in the starter code. - Weights that don't sum to 100. If you mistype one weight, the score is off for every student.
Testing
With the starter marks the program prints Score: 86. With 95, 85 and 75 it prints Score: 81, which checks that every part is rounded down by itself.
