The program is meant to convert a USD($) quantity inputted by the user (from $0 to $10 max) and output it in quantities of quarters, dimes, nickles, and pennies.
I am currently using:
- Linux ParrotOS with Geany 1.37.1
- G++ Compile commands: g++ -std=c++20 -Wall -c "%f"
#include <iostream>
const double QUARTER {0.25};
const double DIME {0.10};
const double NICKLE {0.05};
const double PENNY {0.01};
void dollarToCoin(double cash, unsigned short& quarters, unsigned short& dimes, unsigned short& nickles, unsigned short& pennies){
    
    double cashRemainder = cash;
    quarters = cashRemainder / QUARTER;
    cashRemainder -= QUARTER * quarters;
    dimes = cashRemainder / DIME;
    cashRemainder -= DIME * dimes;
    nickles = cashRemainder / NICKLE;
    cashRemainder -= NICKLE * nickles;
    pennies = cashRemainder / PENNY;
    cashRemainder -= PENNY * pennies;
    std::cout << "Remaining cash: " << cashRemainder << '\n';
}
int main(){
    
    double cash{0};
    unsigned short quarters{0};
    unsigned short dimes{0};
    unsigned short nickles{0};
    unsigned short pennies{0};
    
    std::cout << "Input your cash ($0 - $10 max): ";
    std::cin >> cash;
    dollarToCoin(cash, quarters, dimes, nickles, pennies);
    
    std::cout << "Total quarters: " << quarters <<
    '\n' << "Total dimes: " << dimes <<
    '\n' << "Total nickles: " << nickles << 
    '\n' << "Total pennies: " << pennies << '\n';
    
    return 0;
}
The offending line is nickles = cashRemainder / NICKLE; in the dollarToCoin() function. here is the pseudocode:
- Starting the program, I input 1.2 as an example
- In the dollarToCoin()we copy the cash (1.2 dollars) into thecashRemainder
- We calculate quartersby dividingcashRemainder (1.2) / QUARTER (0.25)= 4.8 we save only the integer and lose the .8 (now we have 4 quarters = $1.00)
- We substract those 4 quarters to the cashRemainder (1.2)giving out0.2
- This is my confusion part: we calculate total of times dimes = cashRemainder(0.2) / DIME (0.1)if I debug this part, it output 1 instead of 2.
If I, however, replace dimes = cashRemaindder / DIME by using --> dimes = 0.2 / DIME this actually outputs 2.
At the end of the program it should convert the input (1.2) into:
Quarters: 4, Dimes: 2, Nickles: 0, Pennies: 0
I still haven't optimized the code nor used any libraries (by which I know there are easier ways) I'm just confused as why this happening.
