I am a beginner and have worked through the greedy algorithm part of PS1 (prompt the user for the amount of change needed, round/convert it to cents, and determine how the change could be dispensed using the smallest number of coins) and have managed to get it to work, but I'm confused as to why my initial code did not work.
I initially used the do/while condition loops for both the input and for each of the four different types of coins (see below, where c is the amount of change and x is the number of coins). While I only had quarters, the output seemed to be correct. However, when I added the condition loops for the other three types of coins, the output was inaccurate (e.g., an input of 0.50 in change would give an output of 5, where it should obviously be 2).
do
{
c = c - 25;
x++;
}
while (c >= 25);
do
{
c = c - 10;
x++;
}
while (c >= 10);
do
{
c = c - 5;
x++;
}
while (c >= 5);
do
{
c = c - 1;
x++;
}
while (c >= 1);
Note: the same inaccurate output resulted when I changed the conditions for the dimes, nickels, and pennies to "while (c >= 10 && c < 25)", "while (c >= 5 && c < 10)"...etc.
However, when I used the following formatting of the do/while condition loops, it seemed to work:
while (c >= 25)
{
c = c - 25;
x++;
}
while (c >= 10)
{
c = c - 10;
x++;
}
while (c >= 5)
{
c = c - 5;
x++;
}
while (c >= 1)
{
c = c - 1;
x++;
}
I'm sure this is an extremely basic issue, but I'm just confused as to why the first block didn't work, so if anyone can shed any light, it would be much appreciated. Thank you!!
c
a float or an int? How was the original value assigned to it? Please edit your question and add the missing code.