2

I have met a strange 9(unexpected) output from printf in C.

The code is:

 1  #include <stdio.h>
 2
 3  int
 4  main(void) {
 5      printf("%lf", 3.14 - 1e20 + 1e20);
 6  }

However, the output is 0.000000.

I do not know how it works.

Can anyone help?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
coolder
  • 144
  • 2
  • 9

1 Answers1

3

The double you're trying to print has 53 bits of precision and 11 bits of exponent. 1e20 (base 10) is 101 0110 1011 1100 0111 0101 1110 0010 1101 0110 0011 0001 0000 0000 0000 0000 0000 in binary (56BC75E2D63100000 in hex). Your 3.14 is too small to be represented once added to a number of that magnitude. Change the order of operations if you want to work around that. This code:

    printf("%f\n", -1e20 + 1e20 + 3.14);

Prints 3.140000.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469