Arithmetic Operators
Rocket Run gives the player an extra life for every 100 coins. With 250 coins, how many lives do they earn, and how many coins are left over? Two C++ operators answer that in one line each, as long as you know how integers divide.
The rule
Integer division drops the remainder; % hands you what was dropped.
The arithmetic operators are +, -, *, / and % (remainder). The key rule: the operand types decide the kind of arithmetic. If both sides of / are integers, the result is an integer and the fraction is simply cut off.
int coins = 250;
int extraLives = coins / 100; // 2
int leftover = coins % 100; // 50
double exact = 250.0 / 100; // 2.5, one side is a doubleA few more tools you will use constantly:
- Compound assignment:
score += 10;meansscore = score + 10;. The same works for-=,*=,/=and%=. - Increment and decrement:
++level;adds one,--lives;subtracts one. - Precedence:
*,/and%happen before+and-, just as in school maths. Use parentheses when in doubt. - Negative numbers: division rounds toward zero, so
-7 / 2is-3and-7 % 2is-1.
% only works on integers. For floating-point remainders there is std::fmod.
The shortcut
Before you calculate, look at the types of the two operands. Both integers means integer arithmetic, whatever variable the answer is stored in.
The code
int total = 17; int rounds = 4; double avg = total / rounds;
The trap is trusting the variable on the left. double avg does not reach back and change how the right side was calculated.
One more warning: an int has a maximum value (commonly about 2.1 billion). Adding past it with signed integers is undefined behaviour, so pick a wider type such as long long for big totals.
Drills
Answer fast — trust the rule.
What is 17 / 5 in C++?
What is 17 % 5?
After double avg = 9 / 2;, what does avg hold?
After int score = 10; score += 5 * 2;, what is score?
What is -7 / 2 in modern C++?
Remember
- Integer division drops the remainder;
%hands you what was dropped. - Shortcut: check the operand types before you calculate.
- Trap: storing the result in a
doubledoes not make the division exact.
