Why floating point value such as 3.14 are consider

2020-01-24 13:37发布

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 ?

5条回答
虎瘦雄心在
2楼-- · 2020-01-24 14:20

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

3.140000000000000124344978758017532527446746826171875 (double)

3.1400001049041748046875 (float)

查看更多
三岁会撩人
3楼-- · 2020-01-24 14:24

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.

查看更多
爷、活的狠高调
4楼-- · 2020-01-24 14:28

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楼-- · 2020-01-24 14:33

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.

查看更多
forever°为你锁心
6楼-- · 2020-01-24 14:39

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.

查看更多
登录 后发表回答