0

I'm struggling with the "greedy" assignment from pset1. I tried to use division to get the amount of coins needed and modulo to get the remainder, wrote code with loops, it compiles and runs, it gives the correct output for anything more than 0.1, but for 0.1 and 0.01 it gives output "32768" and "32768".I guess there's a problem in my loop, but so far I haven't been able to spot it. Here's the code:

    while (c >= 25)
{
    coins = c / 25;
    c = c % 25;
}
while (c >= 10)
{
    coins = coins + (c / 10);
    c = c % 10;
}
while (c >= 5)
{
    coins = coins + (c / 5);
    c = c % 5;
}
while (c >= 1)
{
    coins = coins + (c / 1);
    c = c % 1;
}
   printf("%d\n", coins);
}   

If anyone can point me in the right direction, I'll be very grateful.

0

Okay, I got it, so I'll post it for anyone who experiences similar trouble. The problem was in the second loop, because variable "coins" was defined only in the first loop, so if first loop didn't run, it couldn't add "coins" and "c / 10". I fixed it by defining "coins" right before the first loop.

So, now it runs correctly and I'm going to submit it; however, if anyone who reads this can give me an advice about how to maybe simplify the code or make it more elegant, I'll be grateful. :)

1
  • To make the program simple just replace all the while with ' if ' ..it would still work...so you can avoid error working with loops ..ot would make it elegant
    – DD86
    Feb 24 '17 at 9:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .