3. Arithmetic order errors
A subset of logic errors are arithmetic order errors. In maths, you should be familiar with the order of operations when working out a calculation (BODMAS). Or
- Brackets
- Orders
- Division
- Multiplication
- Addition
- Subtraction
Having a standard order means that users can expect to get the same results when they run a calculation, regardless of the program carrying it out.
Arithmetic errors creep in when the programmer forgets the order of operations, and ends up with a result they don't expect:
Line 30: SET startMiles TO 20
Line 31: SET endMiles TO 26
Line 32: SET petrolUsed TO 2
Line 33: SET milesPerGallon TO EndMiles - StartMiles/petrolUsed
Here, the programmer tries calculating miles per gallon incorrectly. If we slot in the numbers, the calculation looks like this
miles per gallon = 26 - 20/2
With BODMAS the answer is going to be 16 which is incorrect. To get the correct answer, brackets must be added, like this
miles per gallon = (26 - 20)/2
which works out as 3 miles per gallon which is now correct. The pseudocode is now:
Line 33: SET milesPerGallon TO (EndMiles - StartMiles)/petrolUsed
Challenge see if you can find out one extra fact on this topic that we haven't already told you
Click on this link: What are some examples of logic errors in programming?