Skip to content

Instantly share code, notes, and snippets.

@edieblu
Created March 24, 2021 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edieblu/be9a88d4834ab2ec2c4b0c8b320c93fb to your computer and use it in GitHub Desktop.
Save edieblu/be9a88d4834ab2ec2c4b0c8b320c93fb to your computer and use it in GitHub Desktop.
#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