0

so I have this code snippet here:

    int main(int argc, char *argv[])
    {
      double cost;
      sscanf(argv[1], "%lf", &cost);
      double money_given;
      sscanf(argv[2], "%lf", &money_given);
      if(money_given < cost)
      {
        printf("Not enough money to cover the costs\n");
        return -1;
      }
      float change = money_given - cost;

      int quarters = change/.25;
      int dimes = (change -0.25*quarters)/.10;
      int nickels = (change -0.25*quarters - 0.1*dimes)/0.05;
      int pennies = (change -0.25*quarters - 0.1*dimes - 0.05*nickels)/0.01;
      printf("%f - 0.25*%d - 0.1*%d - 0.05 * %d\n", change, quarters, dimes, nickels);
      printf("%d = pennies\n",pennies);

      printf("Cost: %f, Money given: %f. \n Change: %f or \n %d quarters, %d dimes, %d nickels,"
              " %d pennies\n", cost, money_given, change, quarters, dimes, nickels, pennies);

  return 0;
}

So, in the line:

 int pennies = (change -0.25*quarters - 0.1*dimes - 0.05*nickels)/0.01;

If I declare the change variable as a variable and the change is 0.46 for example, then the output is: 1 quarter, 2 dimes, 0 nickels, 0 pennies, which is wrong. It should be 1 quarter, 2 dimes, 0 nickels, 1 penny.

I get the right answer when I declare the variable as a float. Why is that? Is there a difference in the arithmetics when I use a double instead of a float?

  • 1
    Do not use `float` or `double` for money. The difference is the different precision `float` and `double` have. – Osiris Sep 27 '18 at 12:26
  • 4
    this coin problem is better done with integers, divide by 100 in the end: no floating point errors. – Jean-François Fabre Sep 27 '18 at 12:26
  • Always prefer `double` (forget `float` exists). To avoid rounding errors add a very small amount to your variables: `cost += 0.000001;`. Warning: in a larger program with many loops this solution is not advisable! – pmg Sep 27 '18 at 12:27
  • `double` has greater precision (can represent more significant digits) than `float`, so yes, you will get different results depending on the computation. Also, be aware that some values like `0.1` *cannot* be represented exactly in binary, so you will get rounding errors regardless. Like others have said, use integral types for currency, scaled to the smallest unit you need to represent (so if you're using cents, 100 = $1.00, where if you're using mils, 1000 = $1.00). – John Bode Sep 27 '18 at 14:44

0 Answers0