Vincent Worsfold Vincent Worsfold - 4 months ago 42
C Question

CS50 pset1 Greedy not working

Like others here, I am trying to make a program called greedy that will tell me the least amount of coins that I have to give someone as change for a given amount of money. I made this but it gives me the wrong amount of coins and I don't know why :(

#include <stdio.h>
#include <cs50.h>
#include <math.h>

int main(void)

{
float given_amount;
int cent_count;
int coin_count = 0;

do
{
printf("What is the amount of change I owe you?\n");
given_amount = GetFloat();
}
while (given_amount < 0);

cent_count = (int)round(given_amount * 100);

while (cent_count > 25)
{
coin_count++;
cent_count -= 25;
}
while (cent_count > 10)
{
coin_count++;
cent_count -= 10;
}
while (cent_count >= 1)
{
coin_count++;
cent_count -= 1;
}

printf("Take these %d coins\n", coin_count);

}


If I tell the program I need to give back
25 cents
the program tells me I have to give the person
7 coins
, but it should just tell me I have to give him
one coin... a quarter
.

LPs LPs
Answer

Your first 2 loops don't take care of value 25 and 10.

In fact your algorithm is giving you 7, that is: 2 coins of 10 cent, and 5 coins of 1 cent.

You must check for them, so:

 while (cent_count >= 25)
 {
     coin_count++;
     cent_count -= 25;
 }
 while (cent_count >= 10)
 {
     coin_count++;
     cent_count -= 10;
 }
Comments