In C++, numbers are stored using specific data types, depending on whether they are whole numbers or decimals. Choosing the right data type ensures efficiency and accuracy in calculations.
Common Numeric Data Types
C++ provides several options for handling numerical values:
int
→ Stores whole numbers without decimals (e.g.,500
,-20
)float
→ Holds floating-point numbers with decimals (e.g.,7.89
,-3.14
)double
→ Similar tofloat
, but with higher precision (e.g.,12.3456789
)
Examples
C++
x
using namespace std;
int main() {
int maxRPM = 10000; // Whole number (integer)
float fuelEfficiency = 5.75; // Floating point number (low precision)
double topSpeed = 299.99; // Floating point number (high precision)
cout << "Max RPM: " << maxRPM << endl;
cout << "Fuel Efficiency: " << fuelEfficiency << " km/L" << endl;
cout << "Top Speed: " << topSpeed << " km/h" << endl;
return 0;
}
Explanation:
int
is used for values without decimals.float
allows decimals but with limited precision.double
provides higher accuracy, making it ideal for complex calculations.
Choosing Between float and double
When dealing with decimals, precision matters.
float
can store about 6 to 7 decimal digits.double
has about 15 decimal digits, making it more accurate.
It is recommended to use double
for most calculations, especially those requiring precision.
Scientific Notation in C++
Floating-point numbers can be represented using scientific notation, where "e"
or "E"
represents powers of 10.
Example
C++
using namespace std;
int main() {
float torque = 75e3; // 75 × 10³ (75,000)
double horsepower = 12E4; // 12 × 10⁴ (120,000)
cout << "Torque: " << torque << " Nm" << endl;
cout << "Horsepower: " << horsepower << " HP" << endl;
return 0;
}
Explanation:
75e3
means 75 × 10³, or 75,000.12E4
means 12 × 10⁴, or 120,000.