Neo_Sci
Neo_Sci

Reputation: 23

int and float division giving 0 as output

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

Answers (2)

Tonny
Tonny

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

MByD
MByD

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

Related Questions