Search code examples
coutputprecisionpost-increment

Explanation about Output in C


So I have the following code snippet in C:

int a = 25, b = 100, c;
if (b++ <= (a * 4))
  c = 3;
else
  c = 20;
printf ("%f\n", (float) (b / c));

When I ran the code, the output returned the value 33.0000. I was expecting the output to be 33.6667. I was wondering why was it so? My calculations are as follows:

  • In line 2, b is incremented post-operation, and therefore while the statement will return true (100 <= 25*4), the value of b after this operation will be 101.
  • In the output, we calculate 101/3, which should return 33.6667
  • This is not the case, however.

Thank you for your help!!


Solution

  • The expression b / c is performing integer division because both operands are integers. This means the resulting value gets truncated.

    If you want to perform floating point division, cast one of the operands to float.

    printf ("%f\n", (float)b / c);