我和一个朋友对这两个函数进行了编码,以回答一个问题:如果给定找零的总价值,您需要找回多少硬币。 宿舍,角钱,镍币和便士:
变化值的大小给我们不同的答案,但是我不确定如何解释这种差异
def num_coins(cents):
coins = [25, 10, 5, 1]
count = 0
for coin in coins:
while cents >= coin:
cents = cents - coin
count += 1
return count
#########
def coin_return(change):
coin_options = [.25,.10,.05,.01]
number_of_coins = 0
for coin in coin_options:
while change >= coin:
number_of_coins += 1
change = change - coin
return number_of_coins
print(coin_return(.24))
print(num_coins(24))
正确的输出是六个,两个角钱和四个便士。 num_coins函数返回此值,但是coin_return函数返回五。这里发生了什么事?我缺少明显的东西吗?
答案 0 :(得分:1)
正如其他人在评论中已经指出的那样,问题是float
的近似值,如您在下面的代码中所见:
def num_coins(cents, coins):
count = 0
for coin in coins:
while cents >= coin:
print(cents)
cents = cents - coin
count += 1
return count
与int
(精确)一起使用:
print(num_coins(24, [25, 10, 5, 1]))
Cents: 24
Cents: 14
Cents: 4
Cents: 3
Cents: 2
Cents: 1
6
与float
一起使用:
print(num_coins(.24, [0.25, 0.10, 0.05, 0.01]))
Cents: 0.24
Cents: 0.13999999999999999
Cents: 0.03999999999999998
Cents: 0.029999999999999978
Cents: 0.019999999999999976
5
您可以使用round()
函数来解决此问题,例如:
def num_coins(cents, coins, precision):
count = 0
for coin in coins:
while round(cents, precision) >= round(coin, precision):
cents = cents - coin
count += 1
return count
print(num_coins(.24, [0.25, 0.10, 0.05, 0.01], 2))
# 6
print(num_coins(24, [25, 10, 5, 1], 0))
# 6
另一种方法是使用math.isclose()
:
import math
def num_coins(cents, coins):
count = 0
for coin in coins:
while cents > coin or math.isclose(cents, coin):
cents = cents - coin
count += 1
return count
print(num_coins(.24, [0.25, 0.10, 0.05, 0.01]))
# 6
print(num_coins(24, [25, 10, 5, 1]))
# 6
或者,您可以坚持使用int
或使用标准库中的decimal
模块。