0

I'm writing what should be a simple programme for an assignment that finds the ideal change to dispense, measured in the number of coins. My solution is to use a a while loop that keeps checking through coins and subtracting them from the customer change until change equals 0. However, I am getting stuck in an infinite loop and am completely stumped as to why.

Here is my code:

while (change > 0.0) {

    for (int i = 0; i < numberOfCoins; i++) {

        if ((change - coins[i]) >= 0.0) {
            change = change - coins[i];
            coinsTally[i] = coinsTally[i] + 1;
            break;
        }
    }
}

change is any value from 0.0 to 0.99, numberOfCoins = 6,

and coins[numberOfCoins] = { 0.5, 0.2, 0.1, 0.05, 0.02, 0.01}

mch
  • 9,424
  • 2
  • 28
  • 42
  • http://floating-point-gui.de/ – nwp Feb 14 '17 at 14:16
  • 1
    Comparison of floats is a bad thing – Colin Feb 14 '17 at 14:17
  • 4
    When working with currency, it is often helpful to convert all values to the smallest denomination. Ex: $1.20 -> 120 cents (US). – 001 Feb 14 '17 at 14:19
  • You need to have an "else" block to your if statement. Once your If condition is not true, change will not get modified and you'll never resolve the condition in the while block. – Trashman Feb 14 '17 at 15:04

0 Answers0