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.
2 + 3 * 4
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
| Expression | Expected | Actual | Result |
|---|---|---|---|
2 + 3 * 4 | 14 | 20 | Fail |
(2 + 3) * 4 | 20 | 20 | Pass |
10 - 3 - 2 | 5 | 5 | Pass |
12 - 6 / 3 | 10 | 2 | Fail |
12 / 3 * 2 | 8 | 8 | Pass |
18 - 6 + 2 | 14 | 14 | Pass |
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.