-1

I solved the python version of "Cash" yesterday but I ran into an issue with my code. I eventually fixed it but the solution seems rather forced to me so I'd love if someone would help me get why what I tried at first didn't work. First, here's the code, the problem's point is to figure out the Minimum ammount of coins with which to add up to a certain ammount of money.

from cs50 import get_float

# Prompt the user for a valid float
money = -1
while money < 0.01:
    money = get_float("Cashed owed: ")

coins = 0
while money >= 0.25:
    money -= 0.25
    coins += 1

while money >= 0.10:
    money -= 0.10
    coins += 1

while money > 0.049:
    money -= 0.05
    coins += 1

while money > 0.0099:
    money -= 0.01
    coins += 1


print(f"{coins}")

In the code you can see the problem I ran into: for the nickels(0.05) and the dimes(0.01) I had to use a ">" conditional and modify the value to which "money" is being compared to. Whenever I would use the ">=" conditional for every comparison, the program would return an incorrect number of coins on some of the test cases:

:) cash.py exists
:( input of 0.41 yields output of 4
    expected "4\n", not "3\n"
:) input of 0.01 yields output of 1
:( input of 0.15 yields output of 2
    expected "2\n", not "5\n"
:) input of 1.6 yields output of 7
:) input of 23 yields output of 92
:) input of 4.2 yields output of 18
:) rejects a negative input like -1
:) rejects a non-numeric input of "foo" 
:) rejects a non-numeric input of "" 

This is solved by modifying the last two operators to ">" but I assume more errors would pop-up if I would continue to test the program while it still has some ">=" and would appreciate any help on figuring this one out. Thanks in advance and I'll clarify anything I might have miswritten, english is not my native language.

  • You can avoid these floating-point issues by representing money in cents as opposed to dollars. – Scott Hunter May 12 '22 at 15:01
  • I thought about floating-point imprecision for a second but I really don't understand what causes it so I figured it was best to ask. What's the problem with the indentation? I'm quite new at this, sorry! Thanks a lot! – Tomás Binaghi May 12 '22 at 15:05
  • My mistake about the indentation. 0.05 and 0.01 cannot be represented exactly in floating point representation. – Scott Hunter May 12 '22 at 15:13

0 Answers0