Learn C++ · lesson 4 of 61 · about 7 minutes
Arithmetic
Share out the loot with + - * / %, and predict when division drops the decimals.
What you'll learn
- Use the arithmetic operators
- Predict integer division
- Use % for remainders
Damage and loot
Games do sums all the time: damage, healing, sharing out loot. C++ has + - * / %.
Watch out for one thing. When both sides of / are ints, the answer is an int too, and the decimals are dropped: 7 / 2 is 3. If either side is a double, you get the decimals: 7 / 2.0 is 3.5. % gives the remainder: 7 % 2 is 1.
Sharing the loot
#include <iostream>
int main() {
int gold = 17;
int heroes = 5;
std::cout << "Each hero gets " << gold / heroes << "\n";
std::cout << "Left over: " << gold % heroes << "\n";
std::cout << "Exactly: " << gold / 5.0 << "\n";
}Output
Each hero gets 3
Left over: 2
Exactly: 3.4Why drop the decimals?
Whole-number sums are among the fastest things a processor does, and games use them everywhere: squares on a map, items in a bag. You can't carry 3.4 potions.
When you do want the decimals, make one side a double, like 5.0.
What's worked out first
#include <iostream>
int main() {
std::cout << 2 + 3 * 4 << " " << (2 + 3) * 4 << "\n";
}Output
14 20Tip
*, / and % happen before + and -. Use brackets when you want a different order.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.