C++ Numbers
Numbers are at the heart of most programs. C++ splits them into two families: integers for whole numbers and floating-point types for values with a decimal part. Knowing the difference helps you avoid surprising results in your calculations.
Integers and Floating-Point Numbers
An int stores whole numbers such as -5, 0, or 42, with no decimal part. When you need fractions, reach for double, which stores numbers like 3.14 or -0.5. There is also float, a smaller and less precise cousin of double that is used when memory is tight.
Integers and doubles together
#include <iostream>
using namespace std;
int main() {
int items = 4;
double price = 2.75;
double total = items * price;
cout << items << " items cost " << total;
return 0;
}Integer Division Surprise
When you divide two integers, C++ throws away any remainder and keeps only the whole part. If you want a decimal result, at least one of the values must be a floating-point number.
Integer vs. double division
#include <iostream>
using namespace std;
int main() {
int a = 7, b = 2;
cout << "Integer: " << (a / b) << endl; // 3
cout << "Double: " << (7.0 / 2) << endl; // 3.5
cout << "Remainder: " << (a % b); // 1
return 0;
}Note: The % operator, called modulo, gives the remainder of an integer division. It works only with integers and is great for tasks like checking whether a number is even.
- int: whole numbers, fast and exact.
- double: decimal numbers with good precision, the usual choice.
- float: decimal numbers with less precision, uses less memory.
- % modulo: the remainder left after integer division.