为什么需要在分配给 C++ 常量的值之后附加 L 或 F?

2022-01-23 00:00:00 types syntax constants c++

我在网上查看了很多地方,但似乎找不到一个很好的解释来说明为什么我们应该在分配给 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 doubledouble 更精确,所以当 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 << "
";
std::cout << "y=" << y << "
";

此代码在我的系统上的输出,其中 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

这里发生的情况是 x 在赋值之前被四舍五入,因为常量被隐式转换为 double,而 8.99999999999999999 不是可表示为 64 位浮点数.(请注意,作为 long double 的表示也不完全精确.9 的第一个字符串之后的所有数字都是试图逼近十进制数 8.99999999999999999 尽可能使用 96 个二进制位.)

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 9s are an attempt to approximate the decimal number 8.99999999999999999 as closely as possible using 96 binary bits.)

在您的示例中,不需要 L 常量,因为 3.0 可以精确地表示为 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).

相关文章