【问题标题】:Magnitude change to function resulting in different answer函数的幅度变化导致不同的答案
【发布时间】:2019-07-30 22:40:06
【问题描述】:

我和一个朋友编写了这两个函数来回答一个问题,即如果给定零钱的总价值,你需要返还多少硬币来换取零钱。 25美分硬币、5美分硬币和硬币:

我们变化值的幅度给了我们不同的答案,但是我不确定如何解释这种差异

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 函数返回 5。这里发生了什么事?我错过了什么明显的东西吗?

【问题讨论】:

标签: python python-3.x


【解决方案1】:

正如其他人已经在 cmets 中指出的那样,问题是 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 模块。

【讨论】:

    猜你喜欢
    • 2020-04-29
    • 2018-05-17
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    相关资源
    最近更新 更多