A print in the middle
Show on a big screenA program can print a wrong fare with no error message.
- Three lines run. Nothing says which is wrong.
- Add
print(off);after thelet offline. - The window shows
off = 6. - It should be 4. Look at the
let offline.
Pick where to put a print below. Read what it shows.
Loading lab…
The rule
A print in the middle shows what a box held right then. That is often not what you assumed. Printing changes nothing else about the run. So a print works as a window. It lets you see inside a box.
A group pays 2 rupees less for each rider after the first. Three riders travelling three stops should cost 20. The call is groupFare(3, 3).
`` function groupFare(riders, stops) { let one = 2 + 2 * stops; let off = 2 * riders; return one * riders - off; } ``
The box one is the fare for one rider. It is 2 + 2 × 3 = 8. This prints 18, because 8 × 3 − 6 = 18. Add print(off); after the let off line. It shows 6. Two riders get the discount, so off should be 2 × 2 = 4. Then 8 × 3 − 4 = 20.
- Print the box, not a guess.
- Print one thing, near the line you doubt.
- Take the prints out when you are done.
Try the lab to finish this lesson.