-1
#include <stdio.h>
void main() {
    float num = 546.327;
    printf("the number is %f\n",num);
    enter code here

}

The out put is 546.327026. When I tried different numbers it always ended up printing 6 numbers after the dot, when the last 3 are random.

Rob
  • 26,989
  • 16
  • 82
  • 98
Isan Rivkin
  • 177
  • 1
  • 15

2 Answers2

5

Floating point numbers are stored in sums of fractions of 1/2^N

First fractional bit is 0.5,Second is 0.25,Third 0.125,etc

So their representation is not exact... If 546.327 cannot be represented summing fractions of 1/2^N it will be approximated to something close... That's why you get the "random digits", they are not random at all, it's just a rounding inaccuracy.

If you try printing another number that can be accurate represented with sums of 1/2^N you will get the exact number. i.e. 546.5, 546.75,etc

Alex Mantaut
  • 3,657
  • 3
  • 35
  • 45
1

It's precision problems.

Single-precision floating-point numbers have a 24-bit mantissa, which is approximately 7.2 decimal digits. The term approximately implies that the conversion between decimal and binary representations can be inexact. The following table shows this conversion problem. The first column gives a decimal value, the second column contains the closest single-precision float representation of that number.

Here is the full Article