printf specify integer format string for float

It doesn’t print 5 because the compiler does not know to automatically cast to an integer. You need to do (int)a yourself.

That is to say,

#include<stdio.h>
void main()
{
float a=5;
printf("%d",(int)a);
}

correctly outputs 5.

Compare that program with

#include<stdio.h>
void print_int(int x)
{
printf("%d\n", x);
}
void main()
{
float a=5;
print_int(a);
}

where the compiler directly knows to cast the float to an int, due to the declaration of print_int.

Leave a Comment