Skip to content

anonymous /gist:5041708

#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
Something went wrong with that request. Please try again.