不能正确打印在C长双 [英] can't print correctly a long double in C

查看:93
本文介绍了不能正确打印在C长双的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打印一个简单的长双,但它不能正常工作

我试过:

 长双LD = 5.32;的printf(LD与乐=%乐\\ n,LD);
的printf(LD与LF = LF%\\ n,LD);
的printf(LD与LG =%了Lg \\ n,LD);

输出:

  LD与乐= -3.209071e-105
LD与LF = -0.000000
LD与LG = -3.20907e-105

通过一个新值:

  LD = 6.72;

输出:

  LD与乐= -1.972024e + 111
LD与LF = -1972024235903379200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000
LD与LG = -1.97202e + 111


解决方案

有一个类似的问题在Windows下的MinGW。如果这不是你使用的是什么,这个答案也许并不适用。

问题是,编译器(GCC)和运行库(微软)是由发生在对不同的想法不同群体实施类型如何长双应需重新presented。 (GCC使用128位的长双;微软使用64位,同样再presentation为双击 。)

再presentation的选择要么是完全合法的,但它们互不兼容。这不是无论是在海湾合作委员会或Microsoft的库中的缺陷,但在MinGW的方式整合它们。

您的选择是使用非MinGW的其他的实现,写或复制code处理长双正确,或者为了避免调用该采取任何库函数参数或返回类型的结果长双(在计算长双不应该是一个问题,只要他们不T调用任何库函数)。例如,您可以转换为双击%G 打印,具有范围和precision有些茫然

另一个(可能更好)的解决方法是用 -D__USE_MINGW_ANSI_STDIO 进行编译,这会导​​致MinGW的使用自己的实施的printf 和朋友,而不是依赖于微软的实​​现。

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 

解决方案

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.

这篇关于不能正确打印在C长双的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆