0

C program float f = 123.456;why f in memory is "123.456001".

#include<stdio.h>
main()
{
    float f = 123.456;
    printf("%f**%10.2f**%.3f\n", f, f, f);
    printf("%f**%e**%g**\n", f, f, f);
}

123.456001

why 0.000001 ?

kangear
  • 2,493
  • 2
  • 31
  • 44

2 Answers2

4

The binary expansion of

123.456

is

1111011.0111010010111100011010100111111011111001110111...

The computer rounds this off to

1111011.01110100101111001

This is the number that is actually stored in the memory.

The decimal expansion of this number is

123.45600128173828125...

which was printed rounded off to

123.456001
Johan Råde
  • 20,480
  • 21
  • 73
  • 110
1

Not every number can be represented exactly by a computer, that would require infinite memory. So floating point number are rounded to the nearest representable number.

Noctua
  • 5,058
  • 1
  • 18
  • 23