gpt4 book ai didi

c++ - long double 的 printf,未知转换类型字符 L

转载 作者:可可西里 更新时间:2023-11-01 11:47:30 27 4
gpt4 key购买 nike

我的程序很简单:

#include <iostream>
#include <stdio.h>

using namespace std;

int main()
{
long double a = 4.5;
printf("%Lg", a);
return 0;
}

编译时,有一个警告:

warning: unknown conversion type character 'L' in format [-Wformat=]|

控制台的输出是

-1.28823e-231

关于打印长 double 的文档非常清楚,它只是说明这种格式的正确参数是 L。我做错了什么?我在 Windows 10 下使用代码块、mingw32-g++ 编译器。

P.S.:cout 产生相同的输出。

最佳答案

你有一个编译器问题:

mingw uses the Microsoft C run-time libraries and their implementation of printf does not support the 'long double' type. As a work-around, you could cast to 'double' and pass that to printf instead.

因此,你需要double double:

On the x86 architecture, most C compilers implement long double as the 80-bit extended precision type supported by x86 hardware (sometimes stored as 12 or 16 bytes to maintain data structure alignment), as specified in the C99 / C11 standards (IEC 60559 floating-point arithmetic (Annex F)). An exception is Microsoft Visual C++ for x86, which makes long double a synonym for double.[2] The Intel C++ compiler on Microsoft Windows supports extended precision, but requires the /Qlong‑double switch for long double to correspond to the hardware's extended precision format.[3]

代替 printf(),使用 std::coutstd::scientific ,例如:

#include  <iostream>
std::cout << "scientific: " << std::endl << std::scientific << a;

最好不要在同一个项目中同时使用stdio.hiostream,因为它们有时会相互干扰。

附言。关于这个主题,还可用的有:std::hexstd::dec(十进制)、std::boolalpha(true、false ) 等等。

关于c++ - long double 的 printf,未知转换类型字符 L,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41243436/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com