1

I'm using a do..while loop in the get_cents function, which has worked for me in the previous problems. What makes this program incorrect?

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

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;
    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)
{
    int cents;
    do
    {
    return get_int("How many cents? \n");
    }
    while (cents < 0);
        
}

int calculate_quarters(int cents)
{
    return cents/25;
}

int calculate_dimes(int cents)
{
    return cents/10;
}

int calculate_nickels(int cents)
{
    return cents/5;
}

int calculate_pennies(int cents)
{
    return cents/1;
}

Check50 claims that the program doesn't reject negative input. How do I fix this?

0

1 Answer 1

1

Never mind, I just solved the problem. The new code for the get_cents function is:

int get_cents(void)
{
    int cents;
    do
    {
    cents = get_int("How many cents? \n");
    }
    while (cents < 0);
    return cents;

}

I returned the value of cents outside of the loop, which fixed the problem. Figured I'd leave this on here in case anybody else has the same issue.

1
  • please accept your answer
    – UpAndAdam
    Commented Dec 28, 2023 at 16:51

You must log in to answer this question.

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