Ash
Ash

Reputation: 3

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:

Thank you for your help!!

Upvotes: 0

Views: 71

Answers (3)

pooja
pooja

Reputation: 81

An integer division of b/c is done before casting it is so you get the output as 33.000.Try casting variable b to float and then perform division operation

Upvotes: 0

Girija
Girija

Reputation: 118

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

Upvotes: 0

dbush
dbush

Reputation: 224532

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

Upvotes: 3

Related Questions