I have written a coin change generator program. The user enters in a subtotal and the program shows the number of coins that will be dispensed based on the subtotal. When I run it, the program outputs the information correctly. However, there is an error showing at the balance when it gets to the pennies. Instead of showing the balance as just '0.0000', the output shows the balance as '-0.0000'. I don't understand why this occurs.
PS. I know you can account for absolute values using the math library, however, for the purposes of this assignment I cannot use it.
#include <stdio.h>
int main()
{
double total_subtotal;
printf("Enter subtotal: ");
scanf("%lf", &total_subtotal); //user enters subtotal
int Toonies = ((total_subtotal * 100) >= 200) ? (int)((total_subtotal * 100) / 200) : 0;
int change_toonie = (int)(total_subtotal * 100) % 200;
double toonie_balance = total_subtotal - (double)(Toonies * 2); //calculating remaining balance after toonies dispensed
int Loonies = change_toonie >= 100 ? (int)change_toonie / 100 : 0;
int change_loonie = change_toonie % 100;
double loonie_balance = toonie_balance - (double)Loonies; //calculating remaining balance after loonies dispensed
int Quarters = change_loonie >= 25 ? (int)change_loonie / 25 : 0;
int change_quarter = change_loonie % 25;
double quarter_balance = loonie_balance - (double)Quarters * 0.25; //calculating remaining balance after quarters dispensed
int Dimes = change_quarter >= 10 ? (int)change_quarter / 10 : 0;
int change_dime = change_quarter % 10;
double dime_balance = quarter_balance - (double)Dimes * 0.10; //calculating remaining balance after dimes dispensed
int Nickels = change_dime >= 5 ? (int)change_dime / 5 : 0;
int change_nickel = change_dime % 5;
double nickel_balance = dime_balance - (double)Nickels * 0.05; //calculating remaining balance after nickels dispensed
int Pennies = change_nickel >= 1 ? (int)change_nickel / 1 : 0;
double penny_balance = nickel_balance - Pennies * 0.01; //calculating remaining balance after pennies dispensed
printf("Sales EXCLUDING tax\n");
printf("Coin Qty Balance\n");
printf("%22.4lf \n", total_subtotal);
printf("Toonies %3d %9.4lf\n", Toonies, toonie_balance);
printf("Loonies %3d %9.4lf\n", Loonies, loonie_balance);
printf("Quarters %3d %9.4lf\n", Quarters, quarter_balance);
printf("Dimes %3d %9.4lf\n", Dimes, dime_balance);
printf("Nickels %3d %9.4lf\n", Nickels, nickel_balance);
printf("Pennies %3d %9.4lf\n", Pennies, penny_balance); //where the error occurs
return 0;
}
This is what the output looks like. The quantity is the number on the left and the remaining balance is the number on the right. I still have to format it correctly so please excuse the formatting.
//user enters 323.51 as subtotal
Sales EXCLUDING tax
Coin Qty Balance
-------- --- ---------
323.5100
Toonies 161 1.5100
Loonies 1 0.5100
Quarters 2 0.0100
Dimes 0 0.0100
Nickels 0 0.0100
Pennies 1 -0.0000