Joker Joker - 1 month ago 4
C Question

Float to int in C unexpected output

I have the following code in C

#include <stdio.h>

int main()
{

float a = 1.88;
a =a - (0.25 * 7 + 0.1 * 1);
a = a *100;
printf("a = %f\n",a );
int b =(int) (a);
printf("b = %d\n", b);
}


The value of b should be
2
but I get the following output-

a = 3.000000
b = 2


Why is it so?

Answer

If you change

printf("a = %f\n",a );

to

printf("a = %.20f\n",a );

it outputs

a = 2.99999952316284179688

As you can see this is not 3.

So the conversion truncates it to 2.