Why do I need to put 3.14f instead of 3.14 to disable all those warnings ? Is there a coherent reason reason for this ?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Do the Java Integer and Double objects have unnece
- Why does const allow implicit conversion of refere
- thread_local variables initialization
相关文章
- 关于C#中 float、double、decimal 的运算不精确的问题。
- How can I convert a f64 to f32 and get the closest
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
Because
double
can approximate 3.14 much better thanfloat
, maybe? Here are the exact values:3.140000000000000124344978758017532527446746826171875 (
double
)3.1400001049041748046875 (
float
)That's what the C++ (and C) standard decided. Floating point literals are of type double, and if you need them to be floats, you suffix them with a
f
. There doesn't appear to be any specifically stated reason as to why, but I'd guess it's a) For compatibility with C, and b) A trade-off between precision and storage.This is probably a standard in C world. Double is preferred since it's more precise and you probably won't see any performance differences. Read this post.
This is not peculiar to MSVC, it is required by the language standard.
I would suggest that it made sense not to reduce precision unless explicitly requested, so the default is double.
The 6 significant digits of precision that a single-precision float provides is seldom sufficient for general use and certainly on a modern desktop processor would be used as a hand coded optimisation where the writer has determined that it is sufficient and necessary; so it makes sense that an explicit visible marker is required to specify a single-precision literal.
C and C++ prefer double to float in a couple of ways. As you noticed, fractional literals are double unless explicitly made floats. Also, floats can't be passed in varargs, they're always promoted to double (in the same way char and short are promoted to int in varargs).
It's probably better to think of
float
as being a contracteddouble
, rather thandouble
being an extendedfloat
. That is,double
is the preferred floating point type, andfloat
is used whenever a smaller version ofdouble
is required for some particular case. That's the closest I know to a coherent reason, and then the rule makes sense, even if you happen to be in the case where you need a smaller version.