Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i make it so my code looks for the minimum amount of coins?

Tags:

c++

c

I am on Pset1 of EDX:Computer Science, and im in the end of the "Time for change". Here youre supposed to make a code that, once given a number, is supposed to find the least amount of coins you would need. I already made my code, but i cant seem to find how to make it so it find minimum. Here is my code:

{
    printf ("How much do I owe you?\n");            //Get a non-negative number
    float change =  GetFloat();

    while (change < 0)
    { 
        printf ("Please enter a non-negative number\n");
        change = GetFloat();
    }

    int total = 0;

    while (change >=.25)
    {
        change = change - .25;
        total++;
    }
    while (change >=.1 && change <.25)
    {
        change =  change - .1;
        total++;
    }
    while (change >=.05 && change <.10)
    {
        change = change - .05;
        total++;
    }
    while (change > 0 && change <.05)
    {
        printf ("%i\n", total);
    }

When I put in .15, it gives me an answer of 3, but its supposed to say 2. also, some other things I do do give me a number, but its not minimum. How can i make it so it always find the minimum amount?

like image 836
CrazyRussainProgrammer Avatar asked Jan 23 '26 18:01

CrazyRussainProgrammer


1 Answers

First thing you should do is not use a floating point number to represent currency. Arithmetic operations involving floating points numbers are not precise enough to be used for currency. Change it into an int. After that you can use / and % to compute the number of coins.

int amountOwed = ...;      // Amount owed in cents

int total = amountOwed/25; // Number of quarters.
amountOwed = amountOwed % 25; // Amount after the number of quarters.

total += amountOwed/10; // Number of dimes.
amountOwed = amountOwed % 10; // Amount after the number of dimes.

total += amountOwed/5; // Number of nickels.
amountOwed = amountOwed % 5; // Amount after the number of nickels.

// Whatever is left is number of pennies.
total += amountOwed; // Number of pennies.
like image 126
R Sahu Avatar answered Jan 26 '26 09:01

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!