Search code examples
ccs50greedy

Greedy algorithm compiles with no errors but never gets past first action when run


So I am taking cs50 and I am doing the greedy algorithm "cash" problem, and the code I've written compiles fine, but when I run it, it asks for "Change amount in USD:" and then never accepts a valid response and I'm stuck entering inputs forever and nothing happens.

A friend said that I was missing an input and that's why it wasn't working, but I'm trying to use the user's input, so... Your help would be greatly appreciated, because I think I'm really close, I just have not idea how to fix it, and help50 says that technically nothing's wrong, so I'm just at a stand still.

Thank you!

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

int main(void)
{
    // identifying variables
float amount;
int cents;
int count = 0;

// prompting user for input
do
{
    amount = get_float("Change amount in USD: ");
}
// ensuring a positive number
while (amount < 0);

//changing float to an int
    cents = round(amount*100);

// using highest denomination first (quarters)
while (cents % 25 >= 0)
{
    count++;
    cents = cents % 25;
}

// using next highest denomination second (dimes)
while (cents % 10 >= 0)
{
    count++;
    cents = cents % 10;
}

// using next highest denomination third (nickels)
while (cents % 5 >= 0)
{
    count++;
    cents = cents % 5;
}

// using last denomination amount (pennies)
while (cents % 1 >= 0)
{
    count++;
    cents = cents % 1;
}

// displays number of coins used
printf("%i\n", count);

}


Solution

  • Your are stuck in infinite loop since your logic is wrong. Take a look in a while loop, for example:

    while (cents % 25 >= 0)
    {
        count++;
        cents = cents % 25;
    }
    

    modules operation will give you a number between 0 and 24. The condition will always be true regardless of what cents original value was.

    You want to update your condition to a different one. take notice that inside your while you should update cents differently, since after the first iteration cents values will not change: let's say it is 10. It enters the while loop, and then cents=cents%25 will stay 10. Still infinite loop