Arithmetic Operators
Arithmetic operators calculate from their operands. Integer division truncates toward zero, while remainder reports the remainder of integer division.
Compare integer and floating-point calculations at division and overflow boundaries.
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.