Numeric Data Types
Integer Types
Integer types store whole numbers without decimal points. The most commonly used is `int`:
Example
#include <iostream>
using namespace std;
int main() {
int population = 8000000;
int temperature = -10;
cout << "World population: " << population << endl;
cout << "Temperature: " << temperature << "°C";
return 0;
}
Output
World population: 8000000 Temperature: -10°C
Floating-Point Types
For numbers with decimal points, C++ offers `float` and `double`. These are used for approximating real numbers:
Example
#include <iostream>
using namespace std;
int main() {
float weight = 68.5f; // 'f' suffix indicates float
double distance = 384.4e6; // Scientific notation for 384,400,000
cout << "Weight: " << weight << " kg" << endl;
cout << "Distance to Moon: " << distance << " meters";
return 0;
}
Output
Weight: 68.5 kg Distance to Moon: 3.844e+08 meters
Choosing Between float and double
While `float` uses less memory, `double` provides greater precision:
- float: about 7 digits of precision (good for simple measurements)
- double: about 15 digits of precision (better for scientific calculations)
- long double: 19+ digits of precision (for extreme precision needs, platform-dependent)
Example
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float f = 1.23456789f;
double d = 1.234567890123456;
cout << "Float: " << setprecision(6) << f << endl; // ~6 significant digits
cout << "Double: " << setprecision(15) << d; // ~15 significant digits
return 0;
}
Output
Float: 1.23457 Double: 1.23456789012346