Home > OS >  Explanation about Output in C
Explanation about Output in C

Time:01-03

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!!

CodePudding user response:

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);

CodePudding user response:

You have declared b and c a as int in your code and then you have performed a division operation in them which means you are performing the division on integers and the in the result you have converted into float. If you need the division to give exact float value declare the variables as float like,

    int a = 25;
    float b = 100.0, c;
if (b   <= (a * 4))
  c = 3.0;
else
  c = 20.0;
printf ("%f\n",  (b / c));
  • Related