Why does auto deduce this variable as double and not float? [duplicate]

时光怂恿深爱的人放手 提交于 2021-01-19 14:24:14

问题


In the snippet below, auto deduces the variable to double, but I want float.

auto one = 3.5;

Does it always use double for literals with a decimal point? How does it decide between float and double?


回答1:


Type of literal 3.5 is double. For float please use 3.5f

You can play with this snippet to see various type information.




回答2:


3.5 is a double literal. Thus auto correctly deduces its type as double. You can still use it to initialize a float variable, but the most correct way is to use a float literal like 3.5f. The f at the end is called a suffix. Suffixes for floating point literals are:

  • (no suffix) defines double
  • f F defines float
  • l L defines long double

Besides floating point literals, there are also suffixes for integral literals and user-defined literals.




回答3:


In C++ (and C), floating literals are treated as double by default unless specified by f or F or l or L.

The standard has following:

2.14.4 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.

Hence,

auto one = 3.5;

is always double and if you intend float it should be coded as

auto one = 3.5f;



回答4:


The type of a floating point literal in C++ is automatically double unless:

  1. f is suffixed, in which case the type of the literal is float

  2. L is suffixed, in which case the type of the literal is long double

So, if you want your variable to be a float, do this:

auto one = 3.5f;


来源:https://stackoverflow.com/questions/57519313/why-does-auto-deduce-this-variable-as-double-and-not-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!