【问题标题】:I'm creating a function in Python, but I'm not quite getting what I'm expecting [duplicate]我正在用 Python 创建一个函数,但我并没有完全得到我所期望的 [重复]
【发布时间】:2023-02-02 23:02:56
【问题描述】:

我创建了一个函数来将税加到总额中:

def add_tax(amount, tax_rate):
    return new_amount

amount = float(input("Amount: $"))
tax_rate = float(input("Tax Rate (Please enter as decimal i.e 10% -> 0.1): "))


new_amount = amt * (1 + tax_rate)

print(f"Total Amount with Tax: ${new_amount:.2f}")

最后一行我相信我做对了,所以金额四舍五入到小数点后两位。我运行了它,它向我证实它确实四舍五入到小数点后两位。

Amount: $123
Tax Rate (Please enter as decimal i.e 10% -> 0.1): .3456
Total Amount with Tax: $134.56

但是,当我运行函数 add_tax 本身时,它没有四舍五入到小数点后两位:

In:  add_tax(100,0.1)
Out: 110.00000000000001

如何让函数本身也四舍五入到小数点后两位?

【问题讨论】:

  • 在第 2 行中,您有 return new_amount 但未定义 new_amount
  • 您是否忘记复制/粘贴您的一些代码? new_amount 来自哪里?
  • new_amount = amt * (1 + tax_rate)amt 从未定义...
  • 那怎么是重复的? OP 显然只是混淆了字符串和数字。
  • 我的猜测是代码只是被错误地粘贴了,分配 amounttax_ratenew_amount 的行最初在函数内部。也就是说,不需要代码来理解这里的问题。请阅读链接的副本。问题是float 号码基本上不要使用十进制数字,所以它们不能真正被“舍入”——它们只能被调整,这样默认的输出例程将以特定的方式显示它们。 (1/2)

标签: python function decimal


【解决方案1】:
def add_tax(amount, tax_rate):
    new_amount = amount * (1 + tax_rate)
    return new_amount

amount = float(input("Amount: $"))
tax_rate = float(input("Tax Rate (Please enter as decimal i.e 10% -> 0.1): "))

print(f"Total Amount with Tax: ${add_tax(amount, tax_rate):.2f}")

【讨论】:

    猜你喜欢
    • 2013-02-18
    • 2016-08-20
    • 1970-01-01
    • 2021-11-30
    • 2015-12-01
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多