Before you read, I know what is wrong but not how to fix it. See below this paragraph

I'm currently working on greedy.c and I thought I had it down really quickly but I've run into a bug. My greedy code works by first running the change value through a while loop with the condition that it is greater than or equal to 0.25, if so, it subtracts 0.25 from the value until the condition is false. Then the new value goes through another loop with the condition that the value is equal to or greater than .1, and so on until it checks for 0.01(pennies). This works well for some numbers but for 3 cents(.03) it returns that only 2 coins are needed. I made some debugging printf commands that print the value after every loop. Based on the commands the loops execute correctly, then it leaves 0.01 at the end after the final loop. Even when I copied this loop again, it still left 0.01 to pass through it. It is as if 0.01 does not meet the while loop condition but the condition is: while(changeDue>=0.01) {

 while(changeDue>=0.01) { changeDue = changeDue-0.01}

BTW, the way I keep track of how many subtractions are done is by having a variable that increments after each loop. At the end I add these up.

Ok, so I found out it is a floating point value issue b/c the while loops checks for exactly 0.01 but the float will be slightly off! Remember this from the lecture but I never thought it would affect me! The pset instructions seem to suggest I convert to int before I compare. Will try that. Just thought I would keep this up just incase someone else comes cross the same thing! (Although there is another thread on it)


float comparisons are not recommended because they floats are not precise. However, if you feel the necessity to compare floating-point values, you may use an epsilon; this basically tests whether two numbers are close from each others.

You basically choose a margin of error, 0.00001 for example, and given two floats f and g, you may do something like that

set eps to 0.00001
set absDiff to abs(f - g) // could be g - f too

if (absDiff < eps)
    // they are very close

There are other methods in this article!

For this pset, it's recommended to work with ints instead. Be careful though because you may lose data upon casting from float to int.

| improve this answer | |

Pretty simple! Just have to convert the float to int before comparison b/c floats (some) can not be represented in binary so they are changed slightly. The condition checks for the exact value.

| improve this answer | |

You must log in to answer this question.

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