0

Hi I've created the majority of a program that dispenses change given the price of an item however I run into a slight problem when dealing with 5c coins (Australian currency)

  while (change > 0) {

    if ((change - 1.00) >= 0) {
      System.out.printf("$1.00\n");
      change = (change - 1.00);

    } else if ((change - 0.50) >= 0) {
        System.out.printf("$0.50\n");
        change = (change - 0.50);

    } else if ((change - 0.20) >= 0) {
        System.out.printf("$0.20\n");
        change = (change - 0.20);

    } else if ((change - 0.10) >= 0) {
        System.out.printf("$0.10\n");
        change = (change - 0.10);

    } else if ((change - 0.05) >= 0) {
        System.out.printf("$0.05\n");  
        change = (change - 0.05);
    }
  }

for the most part this code DOES dispense the correct change using as few coins as possible however when the change that is to be dispensed uses 5c denominations it just disregards it. for example $1.25 will come out as $1.00 and $0.20.

any help would be greatly appreciated.

p.s It's written in java which I've only started learning in recent weeks.

  • You may well have discovered rounding errors, see http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency – beresfordt Mar 31 '15 at 06:59

1 Answers1

2

Without testing the code I just assume that the problem might be related to rounding errors of the float or double variable change. 1.25 - 1.00 - 0.20 might become slightly less than 0.05.

This would actually lead to an infinite loop, because your code does not terminate when change is smaller than 0.05.

I'd recommend using an int or a long variable and having the price in cents and terminating the loop when the change is smaller than the smallest coin.

If this is not feasible, please have a look at the type BigDecimal that is preferred when you need to deal with money amounts.

Gregor Raýman
  • 3,051
  • 13
  • 19