1. 程式人生 > 實用技巧 >C語言關於long double在Windows下的問題

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;
}

其中書上程式碼:

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

中%Lf為%lf,在Linux中提示錯誤,經查證long double型別數值輸出應為%Lf。
在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);

結果準確無誤。