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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The result of x/y is a
floatand is transferred toprintf()as such.However, you told
printf()using%dto assume the input is anint.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
%din the format string and cast the result of the division toint.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.)