An incomprehensible moment arose in the output of variables of type float.

#include <stdio.h> int main(void) { float a = 123456789; printf("%f",a); return 0; } 

The following code, as I thought, should output 123456789 , however, in a real situation, it outputs 123456792.000000 . If you try to enter something simpler, for example, 900000008, then the last digit disappears. If you make the same thing with the int type, everything is fine. Tell me please, what's the problem?

    1 answer 1

    The problem is that in its 4 bytes, this type must insert not only the value, but also the exponent. Roughly speaking, the representation inside the float is the value reduced to the range [0,1) and the exponent. That is not enough for an accurate presentation.

    (Disclaimer: for connoisseurs - yes, I know, this is a very approximate explanation, about normal and normalized forms, etc. ... I do not think that all this should be told to answer the question asked)

    And in general - do not try to substitute the exact integer by approximate by definition floating-point number ...

    Look, for example, here - https://habrahabr.ru/post/112953/