Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C printf using %d and %f

I was working on this program and I noticed that using %f for a double and %d for a float gives me something completely different. Anybody knows why this happens?

int main ()
{
 float a = 1F;
 double b = 1;

 printf("float =%d\ndouble= %f", a, b);
}

This is the output

float = -1610612736
double = 190359837192766135921612671364749893774625551025007120912096639276776057269784974988808792093423962875123204096.0000
like image 718
user69514 Avatar asked Feb 16 '10 16:02

user69514


People also ask

What does %d and %f means in c?

%d and %f are format specifiers. %d is used for integer(-3,-100,3,100,etc). And %f is used for float(10.6,-39.0,etc).

What is %f in printf in c?

The f in printf stands for formatted, its used for printing with formatted output.

Is %F for double in c?

A double in c can be printed by both using %f and %lf. Both the %f format specifier and the %lf format specifier represent float and double. The printf() in c treats both float and double the same.


1 Answers

%d stands for decimal and it expects an argument of type int (or some smaller signed integer type that then gets promoted). Floating-point types float and double both get passed the same way (promoted to double) and both of them use %f. In C99 you can also use %lf to signify the larger size of double, but this is purely cosmetic (notice that with scanf no promotion occurs and this actually makes a difference).

like image 57
Tronic Avatar answered Oct 21 '22 10:10

Tronic