0

I'm having trouble finding out where the problem with my code is on the Cash problem in the CS50 problem set 1.

In the other questions for this problem on this forum it often seems to be the round() which is missing, but I'm not sure if that is also the issue here, as I am using the cent = round(dollar*100);

When i input 0.41 dollars in the prompt I get the answer 2 coins instead of the correct answer of 4 coins.

Can anybody give me a hint to where i am going wrong?

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

int main(void)
{
    float dollar;
    int cent;

    // Prompts the user to input the amount owed (in dollars)
    do
    {
        dollar = get_float("How much change is owed in dollars?: \n");
        cent = round(dollar*100);
    }
    while (dollar < 0.0);

    // Initialize the amount of coins (will be zero initially)
    int coins = 0;

    //check for the amount of quaters needed
    while (cent >= 0.25)
    {
        cent = cent - 25;
        coins ++;
    }
    //check for the amount of dimes needed
    while (cent >= 10 && cent < 25)
    {
        cent = cent - 10;
        coins ++;
    }
    //check for the amount of nickles needed
    while (cent >= 5 && cent < 10)
    {
        cent = cent - 5;
        coins ++;
    }
    //check for the amount of pennies needed
    while (cent >= 1 && cent < 5)
    {
        cent = cent - 1;
        coins ++;
    }
    //print the lowest amount of coins for the amount of change
    printf("%i\n", coins);
}
4

'while (cent >= 0.25)' here you have accidentally written dollar amount instead of cents.

2
  • Thank you so much, that solved it right away! Think I stared myself blind on the code – larsfoldager Jul 23 '20 at 11:14
  • glad i could help :) – Himanshi Jul 23 '20 at 19:03
0

Here is the code of the core algorithm that I think is more efficient (I converted dollars into cents though), There is no need of loops.

int greedy_cashier_return_coins(int cents){

int coins = 0,temp_cents = cents;

// Suppose 41 / 25 = 1 , then 41 % 25 = 16 (coins: 1)
coins += temp_cents / 25, temp_cents %= 25;

// Continued.. 16 / 10 = 1, then 16 % 10 = 6 (coins: 2)
coins += temp_cents / 10, temp_cents %= 10;

// Continued.. 6 / 5 = 1, then 6 % 5 = 1 (coins: 3)
coins += temp_cents /  5, temp_cents %=  5;

//Return (coins: 3) + (temp_coins: 1) = 4  i.e final coins
return coins += temp_cents;

}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .