Search code examples
ccalculatorcs50greedy

Greedy calculator in C


I need to create a greedy calculator that accepts only .25, .10, .5 and .1. I need to print the minimum amount of coins needed to fulfil the change.

This is going on a loop and I can't see what to do to fix it. I am still learning, go easy on me :)

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

int main(void) {
    int coins = 0;
    int change;
    int i;
    do {
        change = get_float("How much change? ");
    }
    while (change <= 0); /* condition for acceptance*/

    int cents = round(change * 100);

    if (cents > 0) { /* run all whiles we get to 1c*/
        while ((cents - 25) >= 25) { /* run 25c */
            coins += 1;
        }

        while ((cents - 10) >= 10) { /* run  10c*/
            coins += 1;
        }

        while ((cents - 5) >= 5) { /* run  5c*/
            coins += 1;
        }
        while ((cents - 1) >= 1) { /* run  1c*/
            coins += 1;
        }
    } else { 
        printf("%d", coins);
    }
}

Solution

  • There are multiple problems in your code:

    • change is defined as an int, so the amount entered by the user is truncated before the computation even starts, producing an incorrect result.
    • you do not update cents in any of the loops, so you get an infinite loop if any of these conditions is true.
    • note that the conditions are incorrect: (cents - 25) >= 25 is true if cents is greater or equal to 50.

    • the test if (cents > 0) is incorrect. You would only print the number of coins if cents <= 0.

    • the last loop is useless, the number of remaining cents is the number of pennies to count.

    Here is a modified version:

    #include <stdio.h>
    #include <cs50.h>
    #include <math.h>
    
    int main(void) {
        float change;
    
        do {
            change = get_float("How much change? ");
        }
        while (change <= 0); /* condition for acceptance*/
    
        int cents = round(change * 100);  /* avoid rounding issues */
        int coins = 0;
    
        while (cents >= 25) { /* count quarters */
            cents -= 25;
            coins += 1;
        }
        while (cents >= 10) { /* count dimes */
            cents -= 10;
            coins += 1;
        }
        while (cents >= 5) { /* count nickels */
            cents -= 5;
            coins += 1;
        }
        count += cents;  /* count pennies */
        printf("%d\n", coins);
        return 0;
    }