Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <stdio.h>
#include <cs50.h>
#include <math.h>
// quarters (25¢), dimes (10¢), nickels (5¢), and pennies (1¢)
// input of 0.41 yields output of 4
int coins = 0;
int get_change(int cents_remaining, int coin_value)
{
coins += cents_remaining / coin_value;
cents_remaining = cents_remaining % coin_value;
return cents_remaining;
}
int main(void)
{
int coin_values[] = {25, 10, 5, 1};
float dollars = 0;
do
{
dollars = get_float("Change owed:\n");
}
while (dollars < 0);
// convert dollars to int to avoid imprecision
int cents = round(dollars * 100);
for (int i = 0; i < 4; i++)
{
cents = get_change(cents, coin_values[i]);
}
// return the number of coins needed
printf("%i\n", coins);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment