# why does my greedy not give correct outputs?

I have some problems. When I input 4, it should output 4 coins, but it outputs 3 instead. When I input 4.2, it should output 18 but it shows 22 instead. Here's my code:

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

int main(void)
{
float uang_ditukar;
while (true)
{
printf("How much change you have?\$");
uang_ditukar = GetFloat();
if (uang_ditukar >= 0)
break
}

int in_cent = uang_ditukar * 100;

int a = in_cent / 25;
int b = in_cent % 25 / 10;
int c = in_cent % 10 / 5;
int d = in_cent % 5;

int total_coins = a + b + c + d;

if (total_coins > 0)
{
printf("Total number of coin(s): %d\n", total_coins);

if (a >= 1)
printf("%d of 25cent coin: \n", a);

if (b >= 1)
printf("%d of 10cent coin: \n", b);

if (c >= 1)
printf("%d of 5cent coin: \n", c);

if (d >= 1)
printf("%d of 1 cent coin: \n", d);
}
else
{
printf("sorry, no money\n");
}

return 0;
}
``````

thanks for help!

• Even when input 4.2 it shows me 22, rather than 18 coins – Darkstar108 Jul 22 '15 at 6:46

Your code has two problems. First, and one of the prime reasons for this pset, is that you haven't considered how floats are stored. Rather than explain what has happened, I'll simply say this. Put a printf in the code to print out the actual value of in_cent and run the program with 4.2 as input. I think you'll be surprised.

Next is a more serious issue. Your logic for determining the number of coins is creative, but flawed. Here's what's happening with this logic. Let's say that you start with \$0.35. That should be a quarter and a dime. If you apply your code to this, it calculates 1 quarter, then 1 dime, but then, you have `int c = in_cent % 10 / 5;` or (35 % 10 ) / 5 = ( 5 ) / 5 = 1. So, you end up with an extra nickel. (Other inputs can have similar varied outputs.) You have to subtract the value of the larger coins from the total before calculating the smaller denomination coins because of this interaction.

That should get you going. Also, you should know that CHECK50 expects EXACT output. Any other extra output will result in a failure. You need to output exactly what the assignment says, so all those statements will cause you problems (even though they're useful to debug the program.)

Firstly you are using a variable named `uang_ditukar`. If it's something in your mother language, you probably shouldn't. Use only English words and comments so that your code can be read by anyone. Secondly you are not rounding the `float` number your are given. Thirdly your assignments to `a` `b` `c` `d` are wrong. Fourthly all the `printf`s at the end shouldn't be there, as the only output they are expecting is the total number of coins. I would suggest you re-watch the video lectures on this pset. Fifthly you could replace the `while` loop with the `break` command, with a `do-while` loop.