user4685154
user4685154

Reputation:

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?

Upvotes: 2

Views: 81

Answers (2)

Anjaneyulu
Anjaneyulu

Reputation: 434

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

Upvotes: 0

Ed Heal
Ed Heal

Reputation: 59987

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.

Upvotes: 6

Related Questions