0

This is a few lines of prototype code for a program that prints a restaurant menu and records the orders of customers. When I type 15.6 (just a random number I decided to test, it doesn't work for some other numbers too) into the scanf function, it does not seem to store the correct value in the respective variable (in this case, n).

I tried to change n into a float variable but it didn't solve anything. When I do calculations with the n value, the program seems to no longer work properly, regardless of the precision. I created another variable called change which equals to n - total. Theoretically, change should equal to 4.3 when n is 15.6. However, this program prints out "yes" then "no" instead. Is there a way to fix this problem?

void pay () {
  double n, change, total = 11.3;
  printf("\nPlease pay $%0.2f\n", total);
  scanf("%lf", &n);
  printf("%0.6f\n", n);
  if (n == 15.6) {
    printf("yes\n");
    if (n >= total) {
      change = n - total;
      printf("%0.6f\n", change);
      if (change == 4.3) {
        printf("yes\n");
      } else {
        printf("no\n");
      }
    }
  } else {
    printf("no\n");
  }
}
George
  • 1
  • 4
    Please read [Why not use Double or Float to represent currency?](https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency) The decimal numbers `11.3` and `4.3` etc. cannot be exactly represented by a `double` variable. – Weather Vane Apr 02 '20 at 16:58
  • 1
    Also relevant: [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) and [Why Are Floating Point Numbers Inaccurate?](https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate) – Weather Vane Apr 02 '20 at 17:01
  • Oh thanks! I have since used 2 integer variables to represent dollars and cents. – George Apr 04 '20 at 04:05

0 Answers0