Loading

C语言关于long double在Windows下输出错误的问题

最近在学习《C primer plus》这本书,其中一段代码在windows下用vscode+MinGW编译执行出错,代码如下:

#include <stdio.h>
int main(void)
{
    float aboat = 32000.0;
    double abet = 2.14e9;
    long double dip = 5.32e-5;
    printf("%f can be written %e\n", aboat, aboat);
    printf("And it's %a in hexadecimal, powers of 2 notation\n", aboat);
    printf("%f can be written %e\n", abet, abet);
    printf("%Lf can be written %Le\n", dip, dip);
    return 0;
}

在windows下使用MinGW编译运行,此行代码输出并非dip数值。调试运行时,数值确实被赋给dip。随即在Linux环境编译运行此段代码,结果正确。

搜索查询得知:Windows环境下,如果使用的是MinGW,则问题在于默认情况下,MinGW使用I / O响应。Microsoft C运行时提供的格式化功能,该功能不支持80位浮点数(在Microsoft land中为long double== double)。
但是,MinGW还附带了一组替代实现,它们确实支持长双打。要使用它们,请在函数名称前加上__mingw_(例如__mingw_printf)。根据项目的性质,您可能还想全局#define printf __mingw_printf或使用-D__USE_MINGW_ANSI_STDIO(这将启用所有printf-family函数的MinGW版本)。
注:来自printf和long double潇潇雨雨的回答。

经验证,代码换成

__mingw_printf("%Lf can be written %Le\n", dip, dip);

结果准确无误。

posted @ 2020-12-28 13:10  isxh  阅读(590)  评论(1)    收藏  举报