Vincent Worsfold - 6 months ago 75

C Question

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`

`7 coins`

`one coin... a quarter`

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;
}
```