Why floating point value such as 3.14 are consider

2020-01-24 14:26发布

问题:

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 ?

回答1:

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.

2.13.3 Floating literals The type of a floating literal is double unless explicitly specified by a suffix. The suffixes f and F specify float, the suffixes l and L specify long double. If the scaled value is not in the range of representable values for its type, the program is ill-formed.



回答2:

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 contracted double, rather than double being an extended float. That is, double is the preferred floating point type, and float is used whenever a smaller version of double 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.



回答3:

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.



回答4:

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.



回答5:

Because double can approximate 3.14 much better than float, maybe? Here are the exact values:

3.140000000000000124344978758017532527446746826171875 (double)

3.1400001049041748046875 (float)