Hello,
I'm trying to make a program that takes an amount of money from the user
and returns the optimal way to convert it into change.
So, if the user was to input $1.76 the optimal change would be 7 quarters
and 1 penny. For $3.48 the optimal change would be 13 quarters, 2 dime,
and 3 pennies. Etc, etc.
Here is my code for determining change:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
if(toBeChanged >= .25)
{
numberOfQuarters = (int) (toBeChanged / .25);
toBeChanged = fmod(toBeChanged, .25);
}
if(toBeChanged >= .1)
{
numberOfDimes = (int) (toBeChanged / .1);
toBeChanged = fmod(toBeChanged, .1);
}
if(toBeChanged >= .05)
{
numberOfNickels = (int) (toBeChanged / .05);
toBeChanged = fmod(toBeChanged, .05);
}
if(toBeChanged >= .01)
{
numberOfPennies = (int) (toBeChanged / .01);
toBeChanged = fmod(toBeChanged, .01);
}
|
toBeChanged is a double, and the rest of the variables are ints.
The problem is that sometimes it produces the correct amount of change,
but sometimes it's a penny off. Here are some sample outputs to demonstrate
this.
Totally fine, everything adds up:
How much shall I make change for?:.56
Total number of quarters is: 2
Total number of dimes is: 0
Total number of nickels is: 1
Total number of pennies is: 1
|
Not fine, the change is 1 penny short:
How much shall I make change for?:.57
Total number of quarters is: 2
Total number of dimes is: 0
Total number of nickels is: 1
Total number of pennies is: 1
Total amount of change is:4
|
Does anyone know why this is happening?
Thanks.