Loading lessons...
Arithmetic Operators
C++ Arithmetic Operators
Arithmetic operators do the math: +, -, *, /, and %.
The five operators
+adds.-subtracts.*multiplies./divides.%gives the remainder of a division.
A small program
#include <iostream>
using namespace std;
int main() {
int x = 10;
int y = 3;
cout << x + y << endl; // 13
cout << x - y << endl; // 7
cout << x * y << endl; // 30
cout << x / y << endl; // 3
cout << x % y << endl; // 1
return 0;
}
Integer division truncates
When both numbers are whole numbers (int), the result is a whole number. 10 / 3 is not 3.33; it is 3. The decimal part is simply dropped.
cout << 10 / 3 << endl; // 3
cout << 10.0 / 3 << endl; // about 3.33333
To keep the decimals, make at least one number a double.
The remainder is left over
10 % 3 is 1: after putting two whole 3s into 10, there is 1 left over. The % operator answers that question.
TL;DR
- Arithmetic operators:
+,-,*,/,%. - Integer divided by integer truncates the decimals.
- Use a
doubleto preserve a decimal result. %gives the remainder of a division, not the quotient.