I am using the latest gcc with Netbeans on Windows. Why doesn't long double
work? Is the printf
specifier %lf
wrong?
Code:
#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;
}
Output:
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 ...
In C99 the length modifier for
long double
seems to beL
and notl
.man fprintf
(or equivalent for windows) should tell you for your particular platform.If you are using MinGW, the problem is that by default, MinGW uses the I/O resp. formatting functions from the Microsoft C runtime, which doesn't support 80 bit floating point numbers (
long double
==double
in Microsoft land).However, MinGW also comes with a set of alternative implementations that do properly support long doubles. To use them, prefix the function names with
__mingw_
(e.g.__mingw_printf
). Depending on the nature of your project, you might also want to globally#define printf __mingw_printf
or use-D__USE_MINGW_ANSI_STDIO
(which enables the MinGW versions of all theprintf
-family functions).As has been said in other answers, the correct conversion specifier is
"%Lf"
.You might want to turn on the format warning by using
-Wformat
(or-Wall
, which includes-Wformat
) in the gcc invocationFrom the printf manpage:
and
So, you want
%Le
, not%le
Edit: Some further investigation seems to indicate that Mingw uses the MSVC/win32 runtime(for stuff like printf) - which maps long double to double. So mixing a compiler (like gcc) that provides a native long double with a runtime that does not seems to .. be a mess.
Correct Printf conversation in Java :-
In addition to the wrong modifier, which port of gcc to Windows? mingw uses the Microsoft C library and I seem to remember that that this library has no support for 80bits long double (microsoft C compiler use 64 bits long double for various reasons).