Reputation: 23
int main(void)
{
int x;
float y;
x=10;
y=4.0;
printf("%d\n",x/y);
return 0;
}
I compiled this code using a gcc compiler and when run I get 0 as output.
Why is this code giving output as 0 instead of 2?
Upvotes: 2
Views: 1346
Reputation: 671
The result of x/y is a float
and is transferred to printf()
as such.
However, you told printf()
using %d
to assume the input is an int
.
There is no type-checking or automatic type-conversion in this case. printf()
will just execute what you asked. This, by sheer accident, results in a 0 being printed.
You should have specified %d
in the format string and cast the result of the division to int
.
printf("%d\n", (int)(x/y) );
Or you could have used %f
, but then you would have gotten 2.5 as output. (You might want to take a look at the floor() function too.)
Upvotes: 2
Reputation: 137322
IT's not the division, it's the print format.
Change:
printf("%d\n",x/y);
to:
printf("%f\n",x/y);
Upvotes: 7