简体   繁体   中英

Why does printf print the incorrect value?

The following code always prints "0.00" . I was expecting "7888" . Should I convert it to double ?

long l = 7888;
printf("%.2f", l);

%.2f is not a valid format for a long . You can cast it to double:

long l = 7888;
printf("%.2f", (double)l);

Here is a table (scroll a bit down) where you can see which codes are allowed for all number types.

%f expects a double and l variable is a long. printf() does not convert it's arguments to a type required by the format specifier all-by-itself magically.

FWIW, printf() being a variadic function , default argument promotion rule is applied on the supplied arguments, and it does not change a long to double , either. If at all, you want that conversion to happen, you have to cast the argument value explicitly.

You need to write something like

printf("%.2f", (double)l);

Please note, this code invokes undefined behaviour , without an explicit cast. Reference, C11 , chapter §7.21.6.1, fprintf()

[....] If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

The %f format specifier expects a double , but you're passing it a long , so that's undefined behavior.

If you want to print it properly, you need to either use the %ld format specifier to print it as a long :

printf("%ld", l);

Or cast l to double to print it as a floating point number:

printf("%.2f", (double)l);
 I was expecting "7888". 

This happens because you are trying to print LONG with FLOAT identifier. The compiler complains about that if you turn your setting on:

 program.c:5:5: error: format '%f' expects argument of type 'double', but argument 2 has type 'long int' [-Werror=format=] printf("%f", l); ^ cc1: all warnings being treated as errors 

.

 Should I convert it to double? 

By the way you can cast it too, if this is what you really need.

I think this is what you realy need:

#include<stdio.h>

int main(void){
    long l = 7888;
    printf("%ld", l);
    return 0;
}

7888

You cannot printf a long proberly with a float identifier. What do you want do achieve?

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