为什么需要在分配给C ++常量的值之后附加L或F? [英] Why do you need to append an L or F after a value assigned to a C++ constant?
问题描述
我已经在网上查看了几个地方,似乎找不到一个很好的解释,为什么我们应该在分配给C ++常数的值之后添加一个F或L。例如:
I have looked at quite a few places online and can't seem to find a good explanation as to why we should append an F or L after a value assigned to a C++ constant. For example:
const long double MYCONSTANT = 3.0000000L;
任何人都可以解释为什么这是必要的?不是类型声明暗示分配给MYCONSTANT的值是一个长双?上述行和
Can anyone explain why that is necessary? Doesn't the type declaration imply the value assigned to MYCONSTANT is a long double? What is the difference between the above line and
const long double MYCONSTANT = 3.0000000; // no 'L' appended
哇!
推荐答案
默认情况下,浮点常量在C ++中有类型 double
。由于 long double
比 double
更精确,因此当 long double
常量将转换为 double
。要处理这些常量,需要使用 L
后缀来保持 long double
精度。例如,
Floating-point constants have type double
by default in C++. Since a long double
is more precise than a double
, you may lose significant digits when long double
constants are converted to double
. To handle these constants, you need to use the L
suffix to maintain long double
precision. For example,
long double x = 8.99999999999999999;
long double y = 8.99999999999999999L;
std::cout.precision(100);
std::cout << "x=" << x << "\n";
std::cout << "y=" << y << "\n";
在我的系统上输出此代码,其中 double
是64位, long double
96,是
The output for this code on my system, where double
is 64 bits and long double
96, is
x=9
y=8.9999999999999999895916591441391574335284531116485595703125
这里发生的是 / code>在赋值前四舍五入,因为常数隐式转换为
double
和 8.99999999999999999
不能表示为64位浮点数。 (请注意, long double
的表示不完全精确。 9的第一个字符之后的所有数字
s尝试使用96个二进制位尽可能接近十进制数 8.99999999999999999
。
What's happening here is that x
gets rounded before the assignment, because the constant is implicitly converted to a double
, and 8.99999999999999999
is not representable as a 64-bit floating point number. (Note that the representation as a long double
is not fully precise either. All of the digits after the first string of 9
s are an attempt to approximate the decimal number 8.99999999999999999
as closely as possible using 96 binary bits.)
您的示例中,不需要 L
常量,因为 3.0
可以精确地表示为 double
或 long double
。 double
常量值隐式转换为 long double
,不会造成任何精度损失。
In your example, there is no need for the L
constant, because 3.0
is representable precisely as either a double
or a long double
. The double
constant value is implicitly converted to a long double
without any loss of precision.
F
的情况并不那么明显。它可以帮助超载,就像Zan Lynx指出的。我不确定,但它也可以避免一些微妙的舍入误差(即,可能编码作为 float
将给出不同的结果编码为 double
,然后舍入到 float
)。
The case with F
is not so obvious. It can help with overloading, as Zan Lynx points out. I'm not sure, but it may also avoid some subtle rounding errors (i.e., it's possible that encoding as a float
will give a different result from encoding as a double
then rounding to a float
).
这篇关于为什么需要在分配给C ++常量的值之后附加L或F?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!