Skip to content

Instantly share code, notes, and snippets.

Created February 26, 2013 20:10
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 anonymous/5041708 to your computer and use it in GitHub Desktop.
Save anonymous/5041708 to your computer and use it in GitHub Desktop.
#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
/* Note that all of these variables are initialized with undetermined values. This will be important later. */
int quarters, dimes, nickles, pennies;
float quarters_filter, dimes_filter, nickles_filter;
printf("You need change? How much?");
float dollar_amount = GetFloat();
/* I'm curious if you know why this works. */
quarters = dollar_amount / 0.25;
/*
This loop will execute at least once, regardless of the value of dollar_amount.
This is the point of do/while. You want to use while here so that the loop is only
entered if dollar_amount has any quarters to begin with.
*/
do
{
/* I have no idea what quarters_filter is supposed to do */
quarters_filter = dollar_amount - 0.25;
}
while (dollar_amount > 0.25 );
float quarter_reciprocal = quarters_filter - quarters;
dimes = quarter_reciprocal / 0.10;
do
{
dimes_filter = quarter_reciprocal - 0.10;
}
while (quarter_reciprocal > 0.10);
float dime_reciprocal = dimes_filter - dimes;
nickles = dime_reciprocal / 0.05;
do
{
nickles_filter = dime_reciprocal - 0.05;
}
while (dime_reciprocal > 0.05);
float nickle_reciprocal = nickles_filter - nickles;
pennies = nickle_reciprocal / 0.01;
printf("%d\n", quarters);
printf("%d\n", dimes);
printf("%d\n", nickles);
printf("%d\n", pennies);
return 0;
}
/* As I would write it following your approach */
void main()
{
int quarters, dimes, nickles, pennies;
printf("You need change? How much?");
float dollar_amount = GetFloat();
quarters = dollar_amount / 0.25;
while (dollar_amount >= 0.25)
{
dollar_amount -= 0.25;
}
dimes = dollar_amount / 0.10;
while (dollar_amount >= 0.10)
{
dollar_amount -= 0.10;
}
nickles = dollar_amount / 0.05;
while (dollar_amount >= 0.05)
{
dollar_amount -= 0.05;
}
pennies = dollar_amount / 0.01;
printf("%d\n", quarters);
printf("%d\n", dimes);
printf("%d\n", nickles);
printf("%d\n", pennies);
return 0;
}
/* As I would write it following a different approach */
void main()
{
int quarters, dimes, nickles, pennies;
printf("You need change? How much?");
float dollar_amount = GetFloat();
quarters = dollar_amount / 0.25;
dollar_amount -= quarters * 0.25;
dimes = dollar_amount / 0.10;
dollar_amount -= dimes * 0.05;
nickles = dollar_amount / 0.05;
dollar_amount -= nickles * 0.05;
pennies = dollar_amount / 0.01;
printf("%d\n", quarters);
printf("%d\n", dimes);
printf("%d\n", nickles);
printf("%d\n", pennies);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment