Skip to main content
3 of 8
improved formatting
Cliff B
  • 69.3k
  • 4
  • 33
  • 56

Need help with greedy

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

int main(void)

{

float quarter = 0.25, dime = 0.10, nickle = 0.05, penny = 0.01, change;

int coins = 0;

// prompts the user for the value of change in valid parameters
do
{
    printf("How much change is owed?\n");
    change = GetFloat();
    if (change == 0)
    {
        return 0;
    }
}
while (change <= 0);

// takes as many quarters as possible from the value of change
while( quarter < change )
{
    change = change - quarter;
    coins++; 
}

// takes as many dimes as possible from the value of change
while( dime < change )
{
    change = change - dime;
    coins++; 
}

// takes as many nickles as possible from the value of change
while( nickle < change )
{
    change = change - nickle;
    coins++; 
}

 // takes as many pennies as possible from the value of change
while( penny < change )
{
    change = change - penny;
    coins++; 
}

// prints how many coins were used
printf("%i\n", coins);

return 0; 
}

Hey, so this is my code for greedy. When I run it, the amount of necessary coins is slightly imprecise ( when I modify it to a float value, I see just a clean 3.00000 * 10 for example with a roundf for change). For example, when I input 0.41 it shows 3 or 5 to 22, never actually getting the precise amount of coins needed even if the aforementioned modification not in this topic shows a clean floating value.

Please help !