为什么自动将此变量推断为双精度而不是浮点数?

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

在下面的代码片段中,auto 将变量推导为 double,但我想要 float

auto one = 3.5;

带小数点的文字总是使用double吗?它是如何在 float 和 double 之间做出选择的?

文字 3.5 的类型是 double。对于 float 请使用 3.5f

您可以使用 this snippet 来查看各种类型的信息。

3.5double 文字。因此 auto 正确地将其类型推断为 double。您仍然可以使用它来初始化 float 变量,但最正确的方法是使用 float 字面值,例如 3.5f。末尾的 f 称为后缀。浮点文字的后缀是:

  • (无后缀)定义double
  • f F 定义浮点数
  • l L 定义 long double

除了floating point literals, there are also suffixes for integral literals and user-defined literals

在 C++(和 C)中,浮动文字默认被视为 double,除非由 f or F or l or L 指定。

标准有以下内容:

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.

因此,

auto one = 3.5;

始终是 double,如果您打算 float 它应该编码为

auto one = 3.5f;

C++ 中浮点字面量的类型自动为 double 除非:

  1. f 是后缀,在这种情况下,文字的类型是 float

  2. L 后缀,在这种情况下文字的类型是 long double

因此,如果您希望变量成为 float,请执行以下操作:

auto one = 3.5f;