KalimR
KalimR

Reputation: 113

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

Upvotes: 0

Views: 501

Answers (5)

dbush
dbush

Reputation: 223689

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

Upvotes: 7

Sourav Ghosh
Sourav Ghosh

Reputation: 134276

%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.

Upvotes: 8

Michi
Michi

Reputation: 5297

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

Upvotes: 3

Pierre Begon
Pierre Begon

Reputation: 166

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

Upvotes: 1

Glorfindel
Glorfindel

Reputation: 22631

%.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.

Upvotes: 13

Related Questions