-1

I'm trying to solve greed problem for CS50 but it doesn't calculate right. I'm always left with 0.01 instead of 0.00 of rest value. Everything runs smooth except the pennies in the end. I'm not sure what to do. When you input change try 9.99. On number without pennies it works fine.

Thanks a lot!

int main()
{
    // declaring variables for coins

    float const qtr = 0.25;
    float const dimes = 0.10;
    float const nick = 0.05;
    float const penny = 0.01;

    //declaring variables for coin counters

    int qtr_count = 0;
    int dimes_count = 0;
    int nick_count = 0;
    int penny_count = 0;

    //declaring variables for total debt and rest of debt

    float total;
    float rest;

    //loop for testing is the number entered valid

    do
    {
        printf("Enter the ammount of money he owns:\n");
        scanf("%f", &total);
    }
    while (total < 0.00) ;

    rest = total;

    //Loop for calculating coins

    while (rest >= qtr)
    {
        qtr_count++;
        rest -= 0.25;
    }

    while (rest >= dimes)
    {
        dimes_count++;
        rest -= 0.10;
    }

    while (rest >= nick)
    {
        nick_count++;
        rest -= 0.05;
    }

    while (rest >= penny)
    {
        penny_count++;
        rest -= 0.01;
    }

    printf("You need go give: \n %i quarters, \n %i dimes, \n %i nick, \n %i pennies \n", qtr_count, dimes_count, nick_count, penny_count);

    return 0;

}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Bejns
  • 21
  • 1
  • 1
  • 2

1 Answers1

0

The problem is probably that floating point operations are not always exact. I suggest you use integers only. Make the person input the amount in cents (or multiply by 100). That way you will not encounter any problems with floating point operations and it will also be more efficient.

Useless
  • 64,155
  • 6
  • 88
  • 132
Lasse Meyer
  • 1,429
  • 18
  • 38