0

I am attempting the cash exercise (less comfortable) on pset1. I've created four different while loops to help count how many coins change there should be. I tried the program out with just the first while loop and it did work, however, when I have added the other while loops in I get a very large number of coins given for change. Here is my code to help explain what I mean as I must have done something wrong:

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

int main(void)
{
    float dollars;

    do {
       dollars = get_float("How many dollars: ");
    }
    while (dollars < 0);

    float cents;
    cents = dollars * 100;

float quarter = 0.25;
float dime = 0.10;
float nickel = 0.05;
float cent = 0.01;

int count;

while (cents > quarter)
{
    cents = cents - 25;
    count = count + 1;
}

while (cents > dime)
{
    cents = cents - 10;
    count = count + 1;
}

while (cents > nickel)
{
    cents = cents - 5;
    count = count + 1;
}

while (cents > cent)
{
    cents = cents - 1;
    count = count + 1;
}

printf ("Number of coins change is %i\n", count);

}

All of the tests I have done have come out with a large number of coins. I thought this would be because the 'cents' variable was reset after every while loop, but even when I give an input of $0.02 it still gives me an answer of 4327809 coins in change.

Could someone please help me find the bugs in my code? Or am I going about this problem set completely wrong? Any help is much appreciated.

Thanks, Dan

1

You have changed to using cents, but quarter and so on are still in dollars.

Variables like count, declared in the function, not globally, are not initialised by default, so start at any value (maybe zero, but maybe not). Explicitly initialise those, like int count = 0;.

Third, you probably meant cents >= quarter, not >.

Also, good luck with 4.2. round or one of its siblings might help with binary floating point not being able to accurately represent decimal numbers.

1
  • That all makes sense, thanks for your help! Jan 24 '18 at 19:44

You must log in to answer this question.

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