问题
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
fFdefines floatlLdefines 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:
fis suffixed, in which case the type of the literal isfloatLis suffixed, in which case the type of the literal islong 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