C++ floating point types represent numbers with fractional parts.
They provide a much greater range in values.
C++ has two ways of writing floating-point numbers.
The first is to use the standard decimal-point notation:
12.34 // floating-point 987654.12 // floating-point 0.12345 // floating-point 8.0 // still floating-point
The second method called E notation, and it looks like this: 3.45E6.
This means that the value 3.45 is multiplied by 1,000,000.
E6 means 10 to the 6th power, which is 1 followed by 6 zeros.
Thus 3.45E6 means 3,450,000.
The 6 is called an exponent, and the 3.45 is termed the mantissa.
Here are more examples:
1.12e+8 // can use E or e, + is optional 1.12E-4 // exponent can be negative 7E5 // same as 7.0E+05 -12.12e13 // can have + or - sign in front
The following code examines types float and double.
#include <iostream>
using namespace std;
int main() /*from w w w .jav a 2s. c o m*/
{
cout.setf(ios_base::fixed, ios_base::floatfield); // fixed-point
float tub = 10.0 / 3.0; // good to about 6 places
double mint = 10.0 / 3.0; // good to about 15 places
const float million = 1.0e6;
cout << "tub = " << tub;
cout << ", a million tubs = " << million * tub;
cout << 10 * million * tub << endl;
cout << "mint = " << mint << " and a million mints = ";
cout << million * mint << endl;
return 0;
}
The code above generates the following result.
By default, floating-point constants such as 8.24 and 2.4E8 are type double.
If you create a constant to be type float, you use an f or F suffix.
For type long double, you use an l or L suffix.
Here are some samples:
1.234f // a float constant 2.45E20F // a float constant 2.345324E28 // a double constant 2.2L // a long double constant