Return change program decimals c++

1.7k views Asked by At

An exercise for my programming class requires us to write a program for a cashier that prompts the amount of money due and the amount of money received and calculates the change. It also must calculate the amount of dollars, quarters, dimes, nickels, and pennies needed. It works fine up until it gets to the dimes, nickels, and pennies. That is where the output gets wonky. I also noticed that visual studio is reading 0.10 as .1000000000000000056. Same thing with nickels and pennies, but this does not happen with dollars or quarters. I've tried a couple different ways to fix it but have had no luck. Any suggestions

cout << "Amount Due. \n";
double due;
cout << "$";
    cin >> due;

cout << "Amount recieved. \n";
double rec;
cout << "$";
    cin >> rec;

double change = (rec - due);
cout << "Total change= $" << change << " \n";

int dollars = change / 1.00;
change = change - dollars;

int quarters = change / .25;
change = change - quarters;

int dimes = change / .10;
change = change - dimes;

int nickels = change / .05;
change = change - nickels;

int pennies = change / .01;
change = change - pennies;

cout << "Number of dollars: " << dollars << " \n";
cout << "Number of quarters: " << quarters << " \n";
cout << "Number of dimes: " << dimes << " \n";
cout << "Number of nickels: " << nickels << " \n";
cout << "Number of pennies: " << pennies << " \n";

return 0;

}

1

There are 1 answers

0
Oscar Chambers On
while(change > 0){
    if(change >= 1.00){
        dollars ++;
        change -= 1;
        continue;
    }
    if(change >= 0.25){
        quarters ++;
        change -= 0.25;
        continue;
    }
    if(change >= 0.10){
        dimes ++;
        change -= 0.1;
        continue;
    }
    if(change >= 0.05){
        nickels ++;
        change -= 0.05;
        continue;
    }
    if(change >= 0.01){
        pennies ++;
        change -= 0.01;
        continue;
    }
}

The continue keyword starts the loop again from the top. This implementation is resistant to floating point inaccuracies.