Home > Net >  Why is my code not calculating the correct change?
Why is my code not calculating the correct change?

Time:08-11

I'm writing code that asks the user for an integer representing change (get_cents) and is meant to spit out the least number of coins required to make that amount of change. Ex. User inputs 26, it should spit out 2 (one quarter and one penny).

The issue: some of the results I'm getting are incorrect. For example when I input 4, I get 1 instead of 4.

Here is my code:

int get_cents(void);
int calculate_quarters(int cents);
int calculate_dimes(int cents);
int calculate_nickels(int cents);
int calculate_pennies(int cents);

int main(void)
{
    // Ask how many cents the customer is owed
    int cents = get_cents();

    // Calculate the number of quarters to give the customer
    int quarters = calculate_quarters(cents);
    cents = cents - quarters * 25;

    // Calculate the number of dimes to give the customer
    int dimes = calculate_dimes(cents);
    cents = cents - dimes * 10;

    // Calculate the number of nickels to give the customer
    int nickels = calculate_nickels(cents);
    cents = cents - nickels * 5;

    // Calculate the number of pennies to give the customer
    int pennies = calculate_pennies(cents);
    cents = cents - pennies * 1;

    // Sum coins
    int coins = quarters   dimes   nickels   pennies;

    // Print total number of coins to give the customer
    printf("%i\n", coins);
}

int get_cents(void)
{
    // TODO
    //Ask cashier how much cash is owed
    int owed;
    do {
        owed = get_int("Change owed: ");
    }
    while (owed < 0);
    return owed;
}

int calculate_quarters(int cents)
{
    // TODO
    int qs = 0;
    if (cents >= 25) {
        cents -= 25;
        qs  ;
    }

    return qs;
}

int calculate_dimes(int cents)
{
    // TODO
    int ds = 0;
    if (cents >= 10) {
        cents -= 10;
        ds  ;
    }

    return ds;
}

int calculate_nickels(int cents)
{
    // TODO
    int ns = 0;
    if (cents >= 5) {
        cents -= 5;
        ns  ;
    }

    return ns;
}

int calculate_pennies(int cents)
{
    // TODO
    int ps = 0;
    if (cents >= 5) {
        cents -= 1;
        ps  ;
    }
    return ps;
}

Any idea what's going on?

CodePudding user response:

OP is using an if() when cents reduction deserves while().


Instead of either of those, consider a general reduction.

int calculate_coin(int *balance, int coin_value) {
  int coins = *balance / coin_value;
  *balance -= coins*coin_value;
  return coins;
}

and call with

int quarters = calculate_coin(&cents, 25);
int dimes = calculate_coin(&cents, 10);
int nickels = calculate_coin(&cents, 5);
...
  •  Tags:  
  • c
  • Related