简体   繁体   中英

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM