can't print correctly a long double in C

倖福魔咒の 提交于 2019-11-26 09:57:43

问题


I am trying print a simple long double, but it doesn\'t work

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 

回答1:


There's a similar problem with MinGW under Windows. 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 uses 128 bits for long double; Microsoft uses 64 bits, with the same representation as 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.

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). For example, you can convert to double and print with %g, with some loss of range and precision.

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.



来源:https://stackoverflow.com/questions/26296058/cant-print-correctly-a-long-double-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!