0

My method for solving this problem was to use a for loop for each coin, and add the each used to a variable. While it seems that I get the right answer for quarters and dimes, the program ignores nickles when I subtract nickles from the remaining amount. The same goes for pennies. I'm confused because the syntax structure is the same for each loop. Does it have something to do with round(x)?

int main(void) {
float change; int quarters; int dimes; int nickles; int pennies;

int coins = 0;
do
{
    printf("how much change?");
    change = GetFloat();
    for (quarters = 0; change >= 0.25; quarters++)
    {
        change = change - 0.25;

    }
   coins = quarters + coins;
    for (dimes = 0; change >=0.10; dimes++)
    {
        change = change - 0.10;

    }
   coins = dimes + coins;
    for (nickles = 0; change >= 0.05; nickles++)
    {
        change = change - 0.05;

    }
   coins = nickles + coins;
    for (pennies = 0; change >= 0.01; pennies++)
    {
        change = change - 0.01;

    }
    coins = pennies + coins;
    printf("%i\n", coins);
}
while (change < 0);

}

Here are the results of the CS50 check: https://sandbox.cs50.net/checks/41f60d056ae641ae9082a2f8e264b74c

1
  • Sorry to annoy but I still do not understand the implicit conversion. If I convert from float to int, then the result is truncated (depending on the number). I know we don't want that. Though, so far my program accepts both ints and floats. So it seems i'm okay there? I'm not sure. However, I run into issues when I reach pennies since the float-type result of .01 is not ACTUALLY .01 (but more .00999 ... , right?). So my guess is that I need to round somewhere, but if I round at the beginning where I require the user to input a number, the rounding also truncates (change = GetFloat()*100)
    – Emeka A
    Sep 12, 2016 at 22:18

1 Answer 1

2

Have you considered using division and modulo functios instead of subtraction only?

integer division carries only the quotient and modulo only the remainder.

(5 / 3) = 1 (5 % 3) = 2

Will save you a lot of looping.

Enjoy

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