-2

cs50 greedy algorithm description

This is my code for the cs50 greedy algorithm. However, it doesn't output any answer. When I change float dollars to int dollars it works, but only for integers greater or equal to 1. For numbers like 0.32, it returns 0. How do I get my code to work for floats? Any help is appreciated.

#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)
{
    float dollars;
    int quarter = 25;
    int dime = 10;
    int nickel = 5;
    int penny = 1;
    do {
          dollars = get_float("Change owed: ");
    } while(dollars <= 0);

    //convert dollars to cents
    int cents = round(dollars * 100);
    int coins = 0;

    while(cents >= quarter) 
    {
         cents -= quarter; //cents = cents - 25;
         coins++;
    }
    while(cents >= dime) {
        cents -= dime;
        coins++;
    }
    while(cents >= nickel) 
    {
        cents -= nickel;
        coins++;
    }
    while(cents >= penny) 
    {
        cents -= penny;
        coins++;
    }
    printf("%i\n", coins);
}

1 Answers1

0
#include <stdio.h>

#include <math.h>

#include <cs50.h>

float dollars;
int coins = 0;

int main(void)
{
    //Prompt user for Cash owed and keep doing it until a positive number received
    do
    {
        dollars = get_float("Cash owed: ");
    }
    while (dollars <= 0);

    //Round the cents to the nearest penny
    int cents = round(dollars * 100);

    //Iterate deducting the values from the bigger to the smaller
    while (cents > 0)
    {
        if (cents >= 25)
        {
            cents -= 25;
        }
        else if (cents >= 10)
        {
            cents -= 10;
        }
        else if (cents >= 5)
        {
            cents -= 5;
        }
        else
        {
            cents --;
        }
        coins++;
    }
    //Print the minimal amount of coins
    printf("%i\n", coins);
}
Syscall
  • 19,327
  • 10
  • 37
  • 52