I'm reading textbook that says this:
C++ treats all floating-point numbers you type in a program's source code (such as 7.33 and 0.0975) as double values by default.
I find this a bit odd and have never heard of it. Seems wasteful? Why get extra precision if you don't specify it? Why have two different types that mean the same thing? What about a long double?
Any float number can be represented as a double .
A double is named such because it is double the "precision" of a float. Really, what this means is that it uses twice the space of a floating point value -- if your float is a 32-bit, then your double will be a 64-bit.
Checking if a double (or float) is NaN in C++ To check whether a floating point or double number is NaN (Not a Number) in C++, we can use the isnan() function. The isnan() function is present into the cmath library. This function is introduced in C++ version 11. So From C++11 next, we can use this function.
double has 2x more precision than float. float is a 32-bit IEEE 754 single precision Floating Point Number – 1 bit for the sign, 8 bits for the exponent, and 23* for the value. float has 7 decimal digits of precision.
This is a part of language specification. If you want a double, write:
auto a = 12.3;
If you want a float, write:
auto a = 12.3f;
If you want a long double, write:
auto a = 12.3L;
Source: MSDN
The whole topic is extensively described in C++ standard in chapter 2.14 Literals
.
This is referring to floating-point literals only.
This is the same as saying that any integer number you write in code is always treated as a (signed) int
. As soon as you assign this to a variable, you will get the type of the variable.
However, when using standalone literals in computation you will get the type of the literal for that computation, potentially triggering implicit type conversions:
float f = 3.141; // f is of type float, even though the literal was double
auto d = f * 2.0; // d will be of type double because of the literal 2.0
auto f2 = f * 2.0f; // f2 will be of type float again
The computation on the second line involves two different types: The type of the variable f
is float
. Even though it was constructed from a double
literal, the type of the variable is what counts. The type of the literal 2.0
on the other hand is double
and hence triggers an implicit conversion for the computation. The actual multiplication is therefore performed as a multiplication of two double
s.
If you want a standalone value to have a specific type, use the matching literal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With