0

Hi I am trying too create code that takes an amount like 1.35 and counts the minimum amount of coins needed to make change just out of coins, 5 quarters, and 1 dime.

but my code has some interesting errors

example 1.35 shows correct at 5 quarters and 1 dime BUT if it's under a dollar like .35 it shows 1 quarter, 1 nickle, and 4 pennies.

Can someone tell me where my math goes wrong in the following block of code:

#include <iostream>
using namespace std;

//converts dollars into minimum amount of coins. ie input dollar and 22 it will calculate 4 quarters two dimes and two pennies,
const double QUARTER = .25;
const double DIME = .10;
const double NICKLE = .05;
const double PENNY = .01;

int main()
{
    double numberOfQ, numberOfD, numberOfN, numberOfP;
    double total;

    cout << "Please input total amount of money: " << endl;
    cin >> total;

    //while (total > 0) {
    if (total >= .25) {

        numberOfQ = (int)(total / QUARTER);
        total = total - numberOfQ * QUARTER;
        cout << "Number of Quarters: " << numberOfQ << endl;
        cout << "total :" << total << endl;
        
    }
        if (total < 0.25 && total >= 0.10) {
            cout << "total before:" << total << endl;
            numberOfD = (int)(total / DIME);
            total = total - numberOfD * DIME;
            cout << "Number of Dimes: " << numberOfD << endl;
            cout << "total :" << total << endl;
        }
        if (total < 0.1 && total >= 0.05) {
            cout << "total before:" << total << endl;
            numberOfN = (int)(total / NICKLE);
            total = total - numberOfN * NICKLE;
            cout << "Number of Nickles: " << numberOfN << endl;
            cout << "total :" << total << endl;
        }

        if (total < 0.05 && total > 0) {
            cout << "total before:" << total << endl;
            numberOfP = (int)(total / PENNY);
            total = total - (numberOfP * PENNY);
            cout << "Number of Pennies: " << numberOfP << endl;
            cout << "total :" << total << endl;

        }

    //}
    
    


}
  • You'd also want to change the type by `total = total - (int)(numberOfD * DIME);` – vhmvd Jun 06 '22 at 03:44
  • 1
    Also, as a design approach. How about you multiply your input by 100 as `total*=100;` and convert `const double QUARTER = .25;` into `const int QUARTER = 25;`. This will help you navigate out of typecasting. – vhmvd Jun 06 '22 at 03:48
  • 3
    0.35 will be 0.34999999. You really do need to multiply the input by 100 and round to the nearest integer. Otherwise the imprecision of floating point arithmetic will kill you. – Goswin von Brederlow Jun 06 '22 at 03:54
  • @GoswinvonBrederlow and Ahmn21, thanks guys, the imprecision of float point was what was getting me. I converted the consts *100 and I multiplied the total and this fixed everything. – Madison Bratescu Jun 06 '22 at 17:39

0 Answers0