简体   繁体   English

无法在 C 中正确打印 long double

[英]can't print correctly a long double in C

I am trying print a simple long double, but it doesn't work我正在尝试打印一个简单的 long double,但它不起作用

What I tried:我试过的:

long double ld=5.32;

printf("ld with le = %Le \n",ld);
printf("ld with lf = %Lf \n",ld);
printf("ld with lg = %Lg \n",ld);

Output:输出:

ld with le = -3.209071e-105 
ld with lf = -0.000000 
ld with lg = -3.20907e-105 

With a new value:有了新的价值:

ld=6.72;

Output:输出:

ld with le = -1.972024e+111 
ld with lf = -1972024235903379200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000 
ld with lg = -1.97202e+111 

There's a similar problem with MinGW under Windows. Windows 下的 MinGW 也有类似的问题。 If that's not what you're using, this answer probably doesn't apply.如果这不是您使用的,则此答案可能不适用。

The problem is that the compiler (GCC) and the runtime library (Microsoft's) are implemented by different groups that happen to have different ideas about how the type long double should be represented.问题是编译器 (GCC) 和运行时库 (Microsoft 的) 是由不同的团队实现的,他们碰巧对如何表示long double类型有不同的想法。 (gcc uses 128 bits for long double ; Microsoft uses 64 bits, with the same representation as double .) (gcc 对long double使用 128 位;Microsoft 使用 64 位,与double具有相同的表示。)

Either choice of representation is perfectly legitimate, but they're incompatible with each other.两种代表的选择都是完全合法的,但它们彼此不相容。 It's not a bug either in GCC or in Microsoft's library, but in the way MinGW integrates them.这不是 GCC 或 Microsoft 库中的错误,而是 MinGW 集成它们的方式。

Your options are to use an implementation other than MinGW, to write or copy code that handles long double correctly , or to avoid calling any library functions that take arguments or return results of type long double (computations on long double shouldn't be a problem as long as they don't call any library functions).你的选择是使用比其他MinGW的实现,以写或复制代码,手柄long double正确,或避免调用带参数或类型的返回结果的库函数long double (对计算long double不应该是一个问题只要他们不调用任何库函数)。 For example, you can convert to double and print with %g , with some loss of range and precision.例如,您可以转换为double并使用%g打印,但范围和精度会有所损失。

Another (probably better) workaround is to compile with -D__USE_MINGW_ANSI_STDIO , which causes MinGW to use its own implementation of printf and friends rather than relying on the Microsoft implementation.另一个(可能更好)的解决方法是使用-D__USE_MINGW_ANSI_STDIO进行编译,这会导致 MinGW 使用它自己的printf和朋友的实现,而不是依赖于 Microsoft 的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM