#include <stdio.h>
int main()
{
float a = 5;
printf("%d", a);
return 0;
}
This gives the output:
0
Why is the output zero?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With