There is some glitch in my program greedy.c for pset1. My logic to solve the problem is that if I receive change from the user then I am treating the integer part and fractional part separately. For example if I have a change of 1.2$ then for 1(integer part) I'll get 4 quarters and for .2(fractional part) I'll get two dimes. To check my execution for the fractional part I took two variables k and n where k stores the fractional part and n stores the rounded off fractional part i.e k = change - (int)change; *n = k * 100;* This code perfectly works for some inputs like 1.2 , 3.2 etc but for some like 4.2 or 80.2, k does store .2000 as the fractional part but n stores 19 when multiplied by 100 and this glitch instead of giving me 2 coins as output for the fractional part starts giving me 6 coins. Please help!
as denoted by the lectures and other resources, floats are not precise. that is, 4.2 may not necessarily get stored as 4.2. instead, it may be stored as 4.1999999. when subtracting the integer part, the 4, and multiplying the result by 100, you get nearly 0.1999999 * 100 = 19.99999. when casting that to an int, you end up with 19.
the solution is to use the
roundf function from the math library. watch the walkthroughs in the pset specification page and execute
man round in the terminal for more info!