carl.hiass
carl.hiass

Reputation: 1784

Getting wrong printf output for floats

In the following:

float n1= 3.0;
double n2 = 3.0;
long n3 = 2000000000L;
long n4 = 1234567890L;
printf("%f %Lf %ld %ld\n", n1, n2, n3, n4);

3.000000 1.200000 2000000000 1234567890

Why is 1.2 printed for the second value and not 3.0? I suppose maybe I'm screwing up the float prints -- with float, double, and long double, or what's the reason why the above prints an incorrect result? Is this the correct way to print all decimal-types?

float n1= 3.0F;
double n2 = 3.0;
long double n3 = 3.0L;
printf("%f %f %Lf\n", n1, n2, n3);

Upvotes: 0

Views: 109

Answers (1)

Joshua
Joshua

Reputation: 43327

Becaue %Lf isn't the specifier for double, it's the specifier for long double. float promotes to double automatically; hence %f covers both float and double. But long double needs its own.

You kinda got lucky here. On some platforms, the rest of the arguments would be misaligned.

Upvotes: 4

Related Questions