C++ Numbers
Numbers are the values a program counts and measures with. Whole numbers and decimal numbers follow different division rules.
Add, subtract, multiply
Three lines run the three signs on whole numbers. Each line prints one result.
#include <iostream>
int main() {
std::cout << 8 + 3 << "\n";
std::cout << 8 - 3 << "\n";
std::cout << 8 * 3 << "\n";
return 0;
}Two kinds of division
Whole-number division drops the decimal part, so 7 / 2 gives 3. A decimal value keeps the part, so 7.0 / 2 gives 3.5.
#include <iostream>
int main() {
std::cout << 7 / 2 << "\n";
std::cout << 7.0 / 2 << "\n";
return 0;
}Remainder and its sign
The % sign gives what a division leaves behind. The second line shows that the result takes the sign of the first number.
#include <iostream>
int main() {
std::cout << 5 % 2 << "\n";
std::cout << -5 % 2 << "\n";
return 0;
}Multiplication runs first
Multiplication runs before addition here. The expression 2 + 3 * 4 gives 14, not 20.
#include <iostream>
int main() {
std::cout << 2 + 3 * 4 << "\n";
return 0;
}Example
#include <iostream>
int main() {
int a = 14;
int b = 5;
std::cout << "Sum: " << a + b << "\n";
std::cout << "Difference: " << a - b << "\n";
std::cout << "Quotient: " << a / b << "\n";
std::cout << "Float quotient: " << static_cast<double>(a) / b << "\n";
return 0;
}Key points
- Use + to add two numbers.
- Use - to subtract one number from another.
- Use * to multiply two numbers.
- Division of two whole numbers drops the decimal part.
- A decimal value in a division keeps the decimal part.
- The % sign gives the remainder after a division.
- Multiplication runs before addition in an expression.
In this example, a holds 14 and b holds 5. The sum is 19 and the difference is 9. Whole-number division gives the quotient 2. A cast to double makes the last division give 2.8.
Note
The remainder takes the sign of the first number. A negative first number gives a negative remainder.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C++ Compiler
Exercise
What does 7 / 2 print?