greedy.c

Here is the reference solution for Problem Set 1, greedy.c

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

float GetAmount() {
    int done = 0;
    float amount = 0.0;
    while (!done) {
        printf("O hai! How much change is owed?\n");
        amount = GetFloat();
        if (amount >= 0.0) {
            done = 1;
        }
    }
    return amount;
}

int DollarsToCents(float dollars) {
    return round(100.0 * dollars);
}

int BiggestCoinIn(int num_cents) {
    if (num_cents >= 25) {
        return 25;
    } else if (num_cents >= 10) {
        return 10;
    } else if (num_cents >=5) {
        return 5;
    } else if (num_cents >=1) {
        return 1;
    } else {
        return 0;
    }
}

// Returns the number of coins needed to represent a non-negative number
// of cents.
int MinimumCoinsForAmount(int num_cents) {
    int num_coins = 0;
    while (num_cents > 0) {
        int coin = BiggestCoinIn(num_cents);
        num_coins++;
        num_cents -= coin;
    }
    return num_coins;
}

int main(void) {
    float num_dollars = GetAmount();
    int num_cents = DollarsToCents(num_dollars);
    int num_coins = MinimumCoinsForAmount(num_cents);
    printf("%d\n", num_coins);
    return 0;
}
Comments