2

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?

  • 2
    It took me 10 seconds to read the first google hit for "C convert float to int": http://c-faq.com/fp/round.html. Your code is truncating, not converting. – marco.m Oct 22 '16 at 08:23
  • 1
    Possible duplicate of [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – EOF Oct 22 '16 at 08:45
  • I suspect you mean "b should be 3 but why it is 2"? Answer is given below. – Jean-Baptiste Yunès Oct 22 '16 at 08:49

2 Answers2

6

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.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
0

When a float is converted to int only the integer part is stored i.e 2.9 only 2 is stored and remaining is truncated. Similar one in the case of division

#include<stdio.h>
main()
{
    int a=12/5;
    printf("%d\n",a);
}

Here the result is 2.4 but .4 is truncated ..

Anjaneyulu
  • 434
  • 5
  • 21