1.9 — Simple math
Read one box at a time. No rush.
Math operators#
C++ can do math, just like a calculator.
| Symbol | Meaning | Example | Result |
|---|---|---|---|
+ | add | 7 + 2 | 9 |
- | subtract | 7 - 2 | 5 |
* | multiply | 7 * 2 | 14 |
/ | divide | 7 / 2 | 3 (!) |
% | remainder | 7 % 2 | 1 |
Expressions#
An expression is anything that makes a value. 2 + 3 is an expression. So is age * 12.
C++
int apples { 5 };int pears { 3 };int fruit { apples + pears };std::cout << "Fruit: " << fruit << '\n';Output
Fruit: 8The integer division surprise#
When you divide two whole numbers, C++ throws away the decimal part.
C++
std::cout << 7 / 2; // prints 3, not 3.5std::cout << 7.0 / 2; // prints 3.5Watch out
int / int gives an int. If you want decimals, make at least one number a decimal, like 7.0.
Order of math#
C++ follows normal math order: * and / before + and -. Use brackets ( ) to choose the order yourself.
C++
std::cout << 2 + 3 * 4; // 14std::cout << (2 + 3) * 4; // 20More about operators in 3.1 — Math operators.
Tip: press ← / → to move between lessons, / to search.