0

I have some troubles on Greedy. My code output 3 instead of 4 when i input 0.41(also i have 0.42 = 4 and 0.43 = 6) Also same problem happen 4.2, instead of 18 my code output 22. I don't understand why i am doing wrong?

Also I didn't use round() function. Am i need it? If i am why?

int main(void)

{

float money;

float quarter = 0.25; //0.25

float dime = 0.10;    //0.10

float nickel = 0.05;  //0.05

float penny = 0.01;   //0.01

int change;    //amount of coins

int count1 = 0;

int count2 = 0;

int count3 = 0;

int count4 = 0;



do

{

// Get input from the user

printf("O hai! How much change is owed?");

    money = GetFloat();

        if (money > 0)

        {
            //Amount of Quarters
            while (money >= quarter)
            {
                money = money - quarter;            
                count1 = count1 + 1;
            }   
            //Amount of Dimes
            while (money >= dime)
            {
                money = money - dime;            
                count2 = count2 + 1;
            }   
            //Amount of Nickels
            while (money >= nickel)
            {    
                money = money - nickel;
                count3 = count3 + 1;
            }   
            //Amount of Pennies
            while (money >= penny)
            {
                money = money - penny;            
                count4 = count4 + 1;
            }

            //Amount of Coins
            change = count1 + count2 + count3 + count4;
            printf("%d\n", change);

        }
    }    
while (money < 0); 
1

Yes you have to use the round() function, because of the float imprecision that is described in this pset, and that's actually the reason of this pset. For example take a look at the following code:

#include <stdio.h>

int main(void)
{
    float foo = 4.2;
    printf("%.20f\n", foo);
    return 0;
}

It has as output:

4.19999980926513671875

because 4.2 can't be stored accurately in binary, that's why you need to use round().

Also take a look at the following answer which is more detailed:

Greedy.c works for all numbers except 4.2

3
  • I understand the point of round but it didn't work for my code. and i also could not figure out why i get 3 instead of 4?
    – Mearex
    Aug 6 '15 at 13:34
  • I would suggest you work with cents which are integer (i.e. 1, 5, 10 and 25) and they don't suffer from the float imprecision. 1 dollar is 100 cents. You can update your code in your question so we can understand what is still wrong.
    – ChrisG
    Aug 6 '15 at 14:42
  • okey i think i got it. If ı still can not make it, i will upgrade. Thanks.
    – Mearex
    Aug 6 '15 at 16:37

You must log in to answer this question.

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