Lesson Studio demos Programming · 15 minutes

The calculator that says 20

Multiplication should come first in 2 + 3 * 4. This calculator adds first. Find the rule that caused the bug, edit it, and make the tests pass.

Open the workbench
Failing test
2 + 3 * 4
Actual 20Expected 14

Reproduce the bug

Test a case with two different operators. Working left to right gives (2 + 3) * 4, or 20. Standard precedence groups the multiplication first, so 2 + (3 * 4) gives 14.

Read the grouping

The parser turns the expression into a tree. Each operator joins two branches. Evaluate the branches before applying the operator that joins them. The root is the last operation.

Buggy(2 + 3) * 45 × 4 = 20

Fixed2 + (3 * 4)2 + 12 = 14

Repair and test

The rule file gives each operator a rank. A higher rank binds first. Operators tied in rank group left to right. Run the current tests, then change the file and run them again.

Use whole numbers, + - * /, and parentheses.

Enter one rank from 1 to 99 per line. Use * = 20 to give multiplication rank 20.

Expression result

20

Computed branches

2 + 3 gives 5. The root multiplies 5 by 4.

Test results
ExpressionExpectedActualResult
2 + 3 * 41420Fail
(2 + 3) * 42020Pass
10 - 3 - 255Pass
12 - 6 / 3102Fail
12 / 3 * 288Pass
18 - 6 + 21414Pass
Compare with a worked repair

Give * and / rank 20 and leave + and - at 10. Operators on the same tier can still group left to right. The parentheses test makes sure explicit grouping still wins.

Try a new case

Predict the result of 18 / (2 + 1) * 2. Say which operation happens first, second, and last. Then try both versions in the workbench.

Check the reasoning

The addition inside parentheses gives 3. The division gives 6. The multiplication gives 12. The second expression stops at ) because + still needs a right operand.