0

For some reason sometimes it gets the answers right and others it gets the answer wrong, I'm stuck so I don't know what to do next.

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

int main(void) {
    float dollars;
    do {
        dollars = get_float("Change Owed: \n");
    }
    while (dollars < 0);

    int cents = round(dollars * 100);

    int counter = 0;
    int counterQ = 0;
    int counterD = 0;
    int counterN = 0;
    int counterP = 0;

    for (int quarter = 0; quarter < cents; quarter += 25) {
        counterQ++;
    } 
    for (int dime = 0; dime < (cents - (counterQ*25)); dime += 10) {
        counterD++;
    }   
    for (int nickel = 0; nickel < (cents - (counterQ*25) - (counterD*10)); nickel += 5) {
        counterN++;
    }
    for (int penny = 0; penny < (cents - (counterQ*25) - (counterD*10) - (counterN*5)); penny += 1) {
        counterP++;
    }

    counter = (counterQ + counterD + counterN + counterP);
    printf("%i\n", counter);
}
  • Even though sometimes it gives "the right answer", does it give "the right coins"? Suggest for debugging purposes print out the counterX variables to see what the coin assortment is. From reading it looks like and input of .26 (26 cents) will give two coins, which looks ok, but they will both be quarters. – DinoCoderSaurus Apr 5 at 21:58
0

Let's look at one of the for loops and what happens as it runs:

for (int quarter = 0; quarter < cents; quarter += 25) {
    counterQ++;
} 

On the first pass, it will first check whether quarter is less than cents. Initially, it's zero, so of course it will be less than cents! But what if cents is, say, 10 cents? It will count one quarter.

So, how can this be dealt with? What should quarter be initialized to at the start of the for loop?

But then (after that correction), what if change were 25 cents? If the test is that quarter is less than change, it wouldn't deduct a quarter even though it should. How can the test be altered to fix this issue?

So, think about how to correct both of these issues for every type of coin! ;-)

Your approach was interesting, I've never seen it done quite this way. But here's a challenge. Can you do it all without for loops or while loops??? the lesson here is that there's usually more than one way to do something. The secret is to find more efficient ways to do them!

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

| improve this answer | |

You must log in to answer this question.

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