Understanding Floating Point
Unlike integers, floating-point variable can hold wide range of values, including fractions and real numbers. For instance, 3.14, -0.1 etc.
The term floating-point
in floating point numbers refers to the dynamic positioning of the decimal point, allowing a variable number of digits before and after it.
There are three different floating point data types: float
, double
, and long double
. These types differ in the precision they offer and are used to represent real numbers in the program. As with integers, C++ does not define the actual size of these types but it does specify minimum size requirements.
- Floating point data types are always signed (can hold positive, negative values, and 0).
Category | Type | Minimum Size | Typical Size |
Floating point | float | 4 bytes | 4 bytes |
double | 8 bytes | 8 bytes | |
long double | 8 bytes | 8, 12, or 16 bytes |
Syntax for Declaring Floating-Point Variables:
Declaring a floating-point variable in C++ follows a straightforward syntax. You specify the data type (float
, double
, or long double
), followed by the variable name and an optional initialization.
float myFloat;
double myDouble;
long double myLongDouble;
If you wish to initialize the variable at the time of declaration, you can do so as follows:
float piFloat = 3.14f; // 'f' suffix indicates a float literal
double piDouble = 3.14159;
long double piLongDouble = 3.141592653589793238L; // 'L' suffix indicates a long double literal
Note that by default, floating point literals default to type double. An f
suffix is used to denote a literal of type float. As shown in the example above – suffixes like f
for float
and l
for long double
ensure that the literal is interpreted as the correct type.
Initialization and Default Values:
float uninitializedFloat; // Uninitialized variable - content is indeterminate
float initializedFloat = 0.0f; // Initialized to 0.0
double uninitializedDouble; // Uninitialized variable - content is indeterminate
double initializedDouble = 0.0; // Initialized to 0.0
long double uninitializedLongDouble; // Uninitialized variable - content is indeterminate
long double initializedLongDouble = 0.0L; // Initialized to 0.0
Printing floating point numbers
Consider the following program:
#include <iostream>
int main()
{
std::cout << 5.0 << '\n';
std::cout << 6.7f << '\n';
std::cout << 9876543.21 << '\n';
return 0;
}
// Output
5
6.7
9.87654e+06
In the first case, the std::cout printed 5, even though we typed in 5.0. By default std::cout
will not print the fractional part of a number if the fractional part is 0.
In the second case, the number prints as we expect.
In the third case, it printed the number in scientific notation.