Printf of long double, unknown conversion type character L

1.3k views Asked by At

my program is pretty simple:

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

using namespace std;

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

When compiled, there is one warning:

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

The output in the console is

-1.28823e-231

The documentation is pretty clear about printing long doubles, it simply states that the correct parameter for this format is L. What am I doing wrong? I'm using codeblocks, mingw32-g++ compiler under Windows 10.

P.S.: cout produces the same output.

1

There are 1 answers

6
sbail95 On

You have a compiler problem:

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.

Therefore, you need 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]

Instead of printf(), use std::cout coupled with std::scientific, for example:

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

It is best not to use both stdio.h and iostream in the same project, as they can sometimes interfere with each other.

PS. On the subject, also available are: std::hex, std::dec (decimal), std::boolalpha (true, false) and more.