# Pset 6 greedy.py help please!

I'm trying to write greedy in Python rather than in C, but am unsure why my code isn't working. It only works if I input an amount of change that can be returned in one type of coin only (i.e. 3.00 which uses only quarters, or 0.20 which uses only dimes). It doesn't work if I do something like 0.12 (dime and 2 pennies) or 0.3 (quarter and nickel). Can someone help?

``````import cs50

def main():
change = float(input("How much change is owed?"))
print (change)

coins = 0

while change > 0:
if change >= 0.25:
change -= 0.25
coins += 1

elif change >= 0.10:
change -= 0.10
coins += 1

elif change >= 0.05:
change -= 0.05
coins += 1

elif change >= 0.01:
change -= 0.01
coins += 1

print (coins)

if __name__ == "__main__":
main()
``````

## 1 Answer

I don't like computing floats (1/100 in binary is an infinite stream of digits, and cannot be stored in a float), so I convert everything to pence/cents first, and later use only integers. You might need to round the number of pence/cents before storing it in an integer, to avoid truncating 13.9999999 to 13.

That's called fixed-point arithmetics, where you store an integer, and keep in mind that this integer is actually a certain multiple of the real value. Finances use that system, as with floats, they would lose dollars to rounding as soon as they deal with millions.

• Thank you! All I had to do was convert "change" into "cents" by multiplying the value by 100 and rounding it. Jan 18, 2017 at 21:05