I finally got my change program to print out some numbers instead of throwing a floating point exception. However, now it is slightly off. Instead of giving 2 quarters, 1 dime, 1 nickel, and 2 pennies, the program only selects one penny and I cannot figure out why from any inspection on the conditionals or structure of the code. I added some checks in each if statement but not even that is printing out, I am incredibly confused now..
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int changeF(float change, float div)
{
int c = change/div;
return c;
}
int main(void)
{
printf("Enter the bill amount:");
float bill = GetFloat();
printf("Enter the payment amount:");
float payment = GetFloat();
float q = .25; float di = .1; float n = .05; float p = .01;
float change = payment - bill;
do
{
if (bill >= 0.0 && payment >= 0.0 && change >= 0.0)
{
if (change >= q)
{
int quarters = changeF(change, q);
printf("%d quarters\n", quarters);
change = change - (.25*quarters);
}
if (change >= di)
{
int dimes = changeF(change, di);
printf("%d dimes\n", dimes);
change = change - (.1*dimes);
}
if (change >= n)
{
int nickels = changeF(change, n);
printf("%d nickels\n", nickels);
change = change - (.05*nickels);
printf("%f change", change);
}
if (change >= p)
{
int pennies = changeF(change, p);
printf("%d pennies\n", pennies);
change = change - (.01*pennies);
printf("%f", change);
}
}
}
while (change > 0.0);
}
Don't think in terms of dollars, but in terms of cents and use integer arithmetic for your calculations. You can still have the user enter a dollar amount by rounding:
The constants for the values will then of course also be integers, namely 25, 10, 5, and 1.
Then your
changeF
function is just an integer division. (You can forgo the division by one for the pennies - just make the rest of the change pennies.)You don't even need the
do
...while
loop. It is enough to do the calculation just once. Look for quarters, dimes and nickels and the rest is pennies. Done. No need to re-iterate.