1

I run this code

int a, b;
float t;
a = 18642731;  //16777217:16777217 16777216.000000 16777216
t = (float)a;
b = (int)t;
if (a != b)printf("%d %f %d\n", a, t, b);

The output is

18642731 18642732.000000 18642732

The compiler is gcc 9.3.0. Why is t not the value of 18642731.000000

Sun
  • 21
  • 2
  • It's because the IEEE standard see https://en.wikipedia.org/wiki/IEEE_754 – Lala5th Aug 07 '21 at 09:14
  • 2
    `18642731` in binary is `1000111000111011100101011` which needs 26 bits. The IEEE `float` (single-precision) type has `24 + 1` bits of precision. – pmg Aug 07 '21 at 09:17
  • int and float have the same size in most implementations, so obviously for float to have larger range then it'll lose some precision. Duplicates: [Strange behavior when casting an int to float in C](https://stackoverflow.com/q/27113114/995714), [Understanding casts from integer to float](https://stackoverflow.com/q/50319530/995714), [Casting int to float changes value](https://stackoverflow.com/q/54812314/995714) – phuclv Aug 07 '21 at 09:23
  • 1
    Oops ... single precision IEEE floating point has `23 + 1` bits of precision. My previous comment is wrong in this regard. – pmg Aug 07 '21 at 09:29
  • 3
    An easy way to see the problem is this: in that platform both `int`s and `float` use 4 bytes and there are 4294967296 possible distinct quadruplets of bytes. There are indeed 4294967296 distinct values for signed integers (from -2147483648 to 2147483647)... If floats were able to represent any integer what combination of 4 bytes should be used for say `0.5`? All of them are already taken by integers! ... this means that if you can have `0.5` (that is not an integer) then some integer must not be representable in a float. – 6502 Aug 07 '21 at 09:31

1 Answers1

1

Why does converting int to float lose precision in C programming language

Because float type is a finite precision floating point type. It cannot represent all numbers. If you convert a non-representable number to float, then you lose precision.

It just so happens that 18642731 is not representable by float on the system where you ran the program.

eerorika
  • 232,697
  • 12
  • 197
  • 326