0
banknotes = [200,100,50,20,10,5,1,0.50,0.25,0.10,0.05,0.01]

amount = float(input("Enter an amount: "))

for i in range (0,len(banknotes)):
    if banknotes[i] <= amount:
        banknote = int(amount // banknotes[i])
        amount = amount - banknote*(banknotes[i])
        print(banknotes[i],"banknotes:",banknote)

For example when I input 86.74, program acts like its 86.73. But somehow when I input 386.74 or almost any other number, it works correctly. I really can't see where the problem is, and I tried online python compiler to see if my IDE is bugged, same thing happened.

  • float comparisons aren't exact – hjpotter92 Aug 03 '20 at 14:49
  • @hjpotter92 Maybe so, but for scales as small as this, floating-point inaccuracies shouldn't be a problem. – Green Cloak Guy Aug 03 '20 at 14:49
  • I'd suggest you round amount to a number of cents `cents = round(amount * 100)` and then work in integer numbers of cents after that. (ATMs don't generally dispense coins anyway do they?) – Rup Aug 03 '20 at 14:52
  • Oh, that might be the case but I don't know how to fix it... Thanks for the help. I'll check this out. – Ege Boz Aug 03 '20 at 14:53
  • Yes, atms wont work with coins but cashiers do. I shouldnt name this an atm machine – Ege Boz Aug 03 '20 at 14:56
  • If you don't want to do the "Count everything in cents" solution, you can do `banknote = int((amount*100)//(banknotes[i]*100))` instead. I was posting this as an answer but it was closed before I could post. – Cz_ Aug 03 '20 at 15:10

1 Answers1

0

As the comment points out, float comparisons aren't always accurate. if you were to use integers by multiplying by 100 (treat everything as cents and use integer math), this does not become a problem anymore:

banknotes = [20000,10000,5000,2000,1000,500,100,50,25,10,5,1]

# read a floating point into an int, could also just do int(float(input()) * 100)
def parse_input(input_str):
    split = input_str.strip().split(".")
    if len(split) == 2:
        return int(split[0]) * 100 + int(split[1])
    else:
        return int(split[0]) * 100

amount = parse_input(input("Enter an amount: "))

for i in range (0,len(banknotes)):
    if banknotes[i] <= amount:
        banknote = int(amount // banknotes[i])
        amount = amount - banknote*(banknotes[i])
        print("% .2f" % (banknotes[i] / 100,),"banknotes:",banknote)
M Z
  • 4,571
  • 2
  • 13
  • 27