2
#include <stdio.h>
#include <stdlib.h>

int main() {
    float n;
    scanf("%f", &n);
    printf("%.3f", n);
}

input: 51444.325061

my output: 51444.324

expected output: 51444.325

why does I dont get the proper answer?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • How many bits does a float have? – stark Jul 12 '21 at 13:40
  • 3
    Try using a `double`. A `float` only has about 7 digits' worth of precision -- and that's *all* digits, not just digits after the decimal point. So `51444.32` is all you get, and everything after that is suspect. (It's more complicated than that, actually, which is why I said "about 7" and not "exactly 7" -- because it's not exactly 7.) – Steve Summit Jul 12 '21 at 13:41
  • 2
    If you change to `double`, you'll also have to change to `scanf("%lf",&n);`. – Steve Summit Jul 12 '21 at 13:44
  • 1
    Unrelated to the question: But always check the return value of `scanf()`, you code causes UB when `scanf()` fails, which happens when the input is not a number and in some other cases. – 12431234123412341234123 Jul 12 '21 at 15:26

2 Answers2

2

32-bit float can encode about 232 different values.

51444.325061is not one of them**. Instead the nearest float is exactly 51444.32421875. The next best choice would be 51444.328125.

Printing 51444.32421875 to 3 decimal places is best as "51444.324".


why does I dont get the proper answer?

float is too imprecise to encode 51444.325061 as OP desires. Using double will help. The same problem exists, yet only appears when about 16+ significant digits are needed.


** Encodable finite values are of the form: some_integer * 2some_exponent.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
1

Internally, floating-point numbers are not represented as decimal fractions, as you might expect. Instead, they use a floating-point representation based on binary (base-2) numbers.

Because they're base-2, these floating-point numbers cannot represent decimal fractions exactly.

Here are the available float values nearest to 51444.325061, along with their exact decimal equivalents:

0x4748f452  51444.32031250  0.784978032112121582031250 × 2^16
0x4748f453  51444.32421875  0.784978091716766357421875 × 2^16
0x4748f454  51444.32812500  0.784978151321411132812500 × 2^16
0x4748f455  51444.33203125  0.784978210926055908203125 × 2^16

So you can take your pick between 51444.324 or 51444.328. But obviously 51444.324 is closer.

Steve Summit
  • 45,437
  • 7
  • 70
  • 103