-1
float amount;
printf("Enter the amount:\n");
scanf("%f", &amount);
// input: 100.10
printf("%f", amount);

Output: 100.099998

The problem is that the output is not 100.10 same as the input;

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Naim Ibrahim
  • 266
  • 1
  • 2
  • 10
  • 1
    please search SO: similar questions asked thousands of times. Search for float precision representation – Mitch Wheat Oct 17 '13 at 07:32
  • 3
    Floating-point numbers are always stored as the nearest approximation possible and not exact numbers. Read this [**article**](http://www.cygnus-software.com/papers/comparingfloats/Comparing%20floating%20point%20numbers.htm) for a good understanding on storing and comparing floating-point numbers. – TheCodeArtist Oct 17 '13 at 07:34
  • See http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – Arnaud Denoyelle Oct 17 '13 at 07:51

1 Answers1

2

Floating point numbers like 100.10 has no exact binary representations. That's why you encountered rounding error.

Note that there is something more behind, %f in printf actually expects a double argument, so here amount is converted to double in the printf call.

The reason is, variable argument functions like printf always promote their variable argument parts, that's why printf has no format specifier for float, because it always sees double. So a better program to demonstrate your question is to use double instead:

double amount;
printf("Enter the amount:\n");
scanf("%lf", &amount);
printf("%f", amount);

You'll still get rounding error, but no conversion from float to double is done. And to demonstrate the program, you may need to print more digits as double is more accurate.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294