Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf and long double

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 ... 
like image 996
gameboy Avatar asked Nov 03 '10 16:11

gameboy


People also ask

How do I printf a long double?

%Lf format specifier for long double %lf and %Lf plays different role in printf. So, we should use %Lf format specifier for printing a long double value.

What is printf for double?

Format %lf is a perfectly correct printf format for double , exactly as you used it.


2 Answers

Yes -- for long double, you need to use %Lf (i.e., upper-case 'L').

like image 94
Jerry Coffin Avatar answered Oct 04 '22 22:10

Jerry Coffin


From the printf manpage:

l (ell) A following integer conversion corresponds to a long int or unsigned long int argument, or a following n conversion corresponds to a pointer to a long int argument, or a following c conversion corresponds to a wint_t argument, or a following s conversion corresponds to a pointer to wchar_t argument.

and

L A following a, A, e, E, f, F, g, or G conversion corresponds to a long double argument. (C99 allows %LF, but SUSv2 does not.)

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.

like image 29
nos Avatar answered Oct 04 '22 23:10

nos