Debugging methods
3. Arithmetic order errors
Not using arithmetic order properly
In maths, you should be familiar with the order of operations when working out a calculation (BODMAS)
20 + (1+5)/2 - 3*4
First work out the brackets, then multiply and divide, then add or subtract.
Let's look at some broken code (below). This code is to work out miles per gallon. It takes the starting and end mileage of the car and the amount of petrol used.
Line 30: startMiles = 20
Line 31: endMiles = 26
Line 32: petrolUsed = 2
Line 33: milesPerGallon = EndMiles - StartMiles/petrolUsed
In line 33, by slotting in the value of each variable, the miles per gallon value is going to be worked out as
milesPerGallon = 26 - 20/2
The answer produced by this code is 16, which is clearly wrong. This is because the order rules of maths say always divide before subtracting. The correct code in line 33 is
Line 33: milesPerGallon = (EndMiles - StartMiles)/petrolUsed
The brackets have been added to force it to work as intended.