Problem overview
The first version of the report card project computes one number: a student's average across three tests. The starter code stores the scores in three constants, test1, test2 and test3, and the program must print the average as a whole number in the form Average: 85.
With the starting scores 85, 92 and 78, the sum is 255 and 255 divided by 3 is exactly 85, so the program prints Average: 85.
Approach: add, divide, round down
An average is the sum of the values divided by how many there are. JavaScript has one kind of number for both whole and fractional values, so / never throws the remainder away the way integer division does in some other languages. It returns a decimal when the division doesn't come out even. For scores of 90, 90 and 91 the sum is 271, and 271 / 3 is 90.33333333333333.
The lesson wants a whole number, so it wraps the division in Math.floor, which rounds a number down to the nearest integer. For the example above, Math.floor(271 / 3) is 90. The average is rounded down, never to the nearest integer: scores of 100, 100 and 99 average 99.67, and the result is 99.
Step by step
- Create
averagewithconst. It is calculated once and never changes, soconstfits. Add the three tests first and divide the complete sum by 3, then pass the result toMath.floor. - Print the result.
console.logwrites a line to the output, and the lesson's tests read that output. The+operator joins the text"Average: "and the number into one string.
The solution in JavaScript
const test1 = 85;
const test2 = 92;
const test3 = 78;
const average = Math.floor((test1 + test2 + test3) / 3);
console.log("Average: " + average);
Two details are worth noticing:
- The parentheses. Division binds tighter than addition, so the sum has to be wrapped before it is divided. Without the parentheses,
test1 + test2 + test3 / 3divides onlytest3and gives 203 for these scores.Math.floorthen keeps 203, so the program printsAverage: 203. - String plus number. When one side of
+is a string, JavaScript converts the other side to text and joins them. Here that turns 85 into"85"and produces"Average: 85". If both sides were numbers,+would add them.
Edge cases and common mistakes
- Forgetting
Math.floor. For this starter data the average happens to be exactly 85, so the output looks right either way. With other scores, a plain/prints a long decimal such as90.33333333333333. - Using
Math.roundinstead. The lesson rounds down. For 100, 100 and 99,Math.floorgives 99 andMath.roundwould give 100. - Dividing by the wrong number. The divisor is the number of tests, 3, not the largest score or the sum.
- Printing without the label. The output must read
Average: 85, with the colon and one space before the number.
Testing
Change the three constants and compare the output with what you expect:
- 85, 92, 78 gives
Average: 85. - 90, 90, 91 gives
Average: 90. - 100, 100, 99 gives
Average: 99. - 0, 0, 0 gives
Average: 0.
The next version builds on this one.
