如果我不添加额外的"f",后来会不会受到影响?这是速度问题吗?在其他情况下不需要“f”附加项时,是否需要某种含义?
简而言之,为什么我应该使用0.00f而不是0.00?
f
后缀将其作为单精度(float)文字而非双精度文字。这通常意味着32位而非64位浮点数。float
的大小不一定是 32 位
,它是由实现定义的。 - Nawazlong double x=0.1
而不是0.1L
,因为这种错误会导致你无法利用长双精度浮点数的高精度特性,因为你给它提供了一个不够精确的类型。 - Kerrek SB有所不同。 2.00
具有类型 double
,而 2.00f
具有类型 float
。这样做的确切精度和格式影响取决于您的平台。在代码中使用其中之一是否会产生实际差异,取决于其使用的上下文。
作为显式类型变量(基本数字类型)的初始化程序时,不会有区别,但是在函数调用中使用时,可能会影响使用哪个重载或模板特化。
显然,在声明使用 auto
type-specifier 或在 decltype-specifier 中使用表达式时,将影响正在声明的对象的类型。
decltype(2.00) x = 2.00f; // confusing
decltype(2.00f) y = 2.00; // also confusing
auto d = 2.00;
auto f = 2.00f;
float
,由于该值在所有数字类型中都可以精确地表示和正确处理,因此绝对没有区别。2.0
的类型为double
,2.0f
的类型为float
,2
的类型为int
。因此,在参数类型推断中会产生差异。void foo(int) { cure_cancer(); };
void foo(float) { wipe_hard_disk(); }
void foo(double) { exit(0); }
foo(2);
foo(2.0f);
foo(2.0);
2.00
的类型是double
,而2.00f
的类型是float
。
后缀f
将字面量2.00
转换为浮点类型,降低了它的精度。否则,字面量就是double
类型。
double
。指定 f
后缀可以确保它被解释为一个 float
。The suffix affects the type, which changes how a statement is parsed
This not only changes type deduction result via decltype
and function overload selection as others said, but also how an expression is evaluated
For example 2.0 * x / 3
is done in double precision, and 2.0f * x / 3
is done in float precision when x is float
. That may lead to different results because doing in a higher precision will reduce any intermediate errors. It also affects performance greatly on FPU-less systems or systems with an FPU for float
only, and it's a thing embedded programmers need to care about. Demo on Godbolt
Here I'm assuming the FLT_EVAL_METHOD
macro is set so that floating-point types are not evaluated in a higher precision. But even if FLT_EVAL_METHOD >= 1
then the result might still be different with and without the suffix, because of the next point:
The suffix also affects the value
In C++ the value must be rounded correctly to the nearest value in the destination type. So for example when we have
float f1 = 8388608.5000000009f;
float f2 = 8388608.5000000009;
then f1
and f2
will have different values because the suffix prevents double rounding (meaning rounding twice, not the type double
) from happening in f2
(decimal → double → float). The decimal value is rounded to the nearest float
value directly in f1
(decimal → float) without going through double
. Print the values with more precision and you'll see
Another example:
f1 = 7.038531e-26f;
f2 = 7.038531e-26;
There are many other examples that you can see in the demo