It is the order of math operations. C++ follows the standard math operations that you would see in math.
total = two + one / total;
should be..
total = (two + one) / total;
First, let's consider the calculation of the program:
- When
i
is 0, the program runs the else section,one * two
equals to 112, sototal
is increased by 112, and now it's 0 + 112 = 112. - When
i
is 1, the program runs the if section,two + one / total
is2 + 56 / 112
. First, notice thatoperator/
is prior thanoperator+
, so it will be first calculated. Second, if the two numbers of the/
calculation is both integers, the fractional part would be abandoned, so the result of56 / 112
is0
. Then, the result of2 + 56 / 112
is2 + 0
, and that's2
, so the value oftotal
is now2
. - When
i
is 2, the program runs the else section,one * two
equals to 112, sototal
is increased by 112, because it was2
before the addition, it should be2 + 112
=114
now.
In an conclusion, the key point is that because it was 2
before the addition, it should be 2 + 112
= 114
now, and don't forget that if you use operator+=
, the program increases the variable by the value after the operater, but not just setting the variable to the value after the operator.