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?

3
  • 2
    It took me 10 seconds to read the first google hit for "C convert float to int": c-faq.com/fp/round.html. Your code is truncating, not converting. Commented Oct 22, 2016 at 8:23
  • 1
    Possible duplicate of Is floating point math broken? Commented Oct 22, 2016 at 8:45
  • I suspect you mean "b should be 3 but why it is 2"? Answer is given below. Commented Oct 22, 2016 at 8:49

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.