printf和long double

gam*_*boy 52 c printf gcc long-double

我在Windows上使用最新的gcc和Netbeans.为什么不起作用long double?是printf符%lf错了吗?

码:

#include <stdio.h>

int main(void)
{
    float aboat = 32000.0;
    double abet = 5.32e-5;
    long double dip = 5.32e-5;

    printf("%f can be written %e\n", aboat, aboat);
    printf("%f can be written %e\n", abet, abet);
    printf("%lf can be written %le\n", dip, dip);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

32000.000000 can be written 3.200000e+004
0.000053 can be written 5.320000e-005
-1950228512509697500000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000.000000
can be written 2.725000e+002
Press [Enter] to close the terminal ...
Run Code Online (Sandbox Code Playgroud)

nos*_*nos 42

从printf手册页:

l(ell)以下整数转换对应于long int或unsigned long int参数,或者后续n转换对应于指向long int参数的指针,或者后续c转换对应于wint_t参数或后续s转换对应于指向wchar_t参数的指针.

和

跟随a,a,e,E,f,F,g或G转换的LA对应于长双参数.(C99允许%LF,但SUSv2不允许.)

所以,你想要的%Le不是%le

编辑:一些进一步的调查似乎表明Mingw使用MSVC/win32运行时(对于像printf这样的东西) - 它将long double映射为double.因此,混合使用提供本机long double的编译器(如gcc)与运行时似乎并不是一团糟.


Jer*_*fin 37

是 - 因为long double,你需要使用%Lf(即大写'L').


kli*_*bot 24

如果您使用MinGW,问题是默认情况下,MinGW使用I/O resp.Microsoft C运行时格式化函数,它不支持80位浮点数(在Microsoft long double域中== double).

但是,MinGW还提供了一组替代实现,可以正确支持长双精度.要使用它们,请在函数名称前加上__mingw_(例如__mingw_printf).根据项目的性质,您可能还需要全局#define printf __mingw_printf或使用-D__USE_MINGW_ANSI_STDIO(这将启用所有printf-family函数的MinGW版本).


APr*_*mer 14

除了错误的修饰符,gcc到Windows的哪个端口?mingw使用Microsoft C库,我似乎记得这个库不支持80位长双(微软C编译器使用64位长双由于各种原因).


Jas*_*ley 6

有这个问题测试长的双打,唉,我遇到了一个修复!您必须使用-D__USE_MINGW_ANSI_STDIO编译项目:

Jason Huntley @ centurian /home/developer/dependencies/Python-2.7.3/test $ gcc main.c

Jason Huntley @ centurian /home/developer/dependencies/Python-2.7.3/test $ a.exe c = 0.000000

Jason Huntley @ centurian /home/developer/dependencies/Python-2.7.3/test $ gcc main.c -D__USE_MINGW_ANSI_STDIO

Jason Huntley @ centurian /home/developer/dependencies/Python-2.7.3/test $ a.exe c = 42.000000

码:

Jason Huntley@centurian /home/developer/dependencies/Python-2.7.3/test
$ cat main.c
#include <stdio.h>

int main(int argc, char **argv)
{
   long double c=42;

   c/3;

   printf("c=%Lf\n",c);

   return 0;
}
Run Code Online (Sandbox Code Playgroud)


Jen*_*edt 5

在 C99 中,长度修饰符long double似乎是L而不是l。man fprintf(或 Windows 的等效项)应该告诉您特定的平台。

  • 可惜他使用的是 Windows,而且可能没有联机帮助页。不管怎样,谷歌搜索“man printf”或“printf手册页”或类似的东西。 (2认同)