I've stuck with my code. Sometimes it counts correctly but most of the time - it doesn't. The below is a part of my code. I would appreciate if you point out what is wrong with this logic:

float change;
int quarter = 25;
int dime = 10;
int nickle = 5;
int penny = 1;
int leftover0;
int leftover1;
int leftover2;
int leftover3;
int coinq; //amount of quarters
int coind; //amount of dimes
int coinn; //amount of nickles
int coinp; //amount of pennies
int coins;

//round and convert to cents:
int cents;
cents = round(change * 100);

//use the largest coin:

while (quarter <= cents)

leftover0 = cents - quarter;
// coinq keeps track of how many coins of quarter was used:
coinq = (cents - leftover0) / 25;

while (dime <= leftover0)

leftover1 = leftover0 - dime;
coind = (leftover0 - leftover1) / 10;

while (nickle <= leftover1)

leftover2 = leftover1 - nickle;
coinn = (leftover1 - leftover2) / 5;

while (penny <= leftover2)

leftover3 = leftover2 - penny;
coinp = (leftover2 - leftover3) / 1;

coins = coinq + coind + coinn + coinp;

printf("%d\n", coins);
  • Did you watch Zamayla's walkthrough?
    – kzidane
    Feb 22, 2015 at 23:14

2 Answers 2

while (quarter <= cents)

leftover0 = cents - quarter;

The value of the quarter, dimes, nickels, and/or pennies in your code will always stay under the value of cents, so the coins will keep on adding up. Try putting "cents - (//variable)" in the while loop and it might help. Also if you are stuck, watch the walkthrough CS50 provides you.


A few areas of improvement to explore:

while (quarter <= cents)

During this while loop, you are not decrementing the value of cents at all. So "cents" will always stay the same and quarter will keep incrementing. You could add another line of code within your while loop to decrease cents by 1 quarter each time.

If you do this, you don't need to have all of those leftover vars. You can continue to use the cents var throughout the program.

You also don't need a coinq, etc. var for each coin. The value of quarter is going to tell you the number of quarters used, and so on and so forth for each coin type.

in pseudocode:

convert to cents

while quarter >= cents
     cents - 25

while dime >= cents

repeat for each coin type....

coins = quarter + dime + nickel + penny
printf coins

You must log in to answer this question.

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