【问题标题】:Is there somethig i am doing wrong or is the expected output incorrect? [duplicate]我做错了什么还是预期的输出不正确? [复制]
【发布时间】:2020-10-28 17:23:36
【问题描述】:

这是我从hackerrank的30天代码中得到的第三个问题(https://www.hackerrank.com/challenges/30-operators/problem)

任务:

给定一餐的餐费(餐费的基本成本)、小费百分比(作为小费添加的餐费百分比)和税费百分比(作为税款添加的餐费百分比),求并打印这顿饭的总费用。

示例输入:

12.00

20

8

注意:请务必使用精确值进行计算,否则您可能会得到不正确的四舍五入结果! Explanation

def solve(meal_cost, tip_percent, tax_percent):
    tip = (tip_percent/100) * meal_cost
    tax = (tax_percent/100) * meal_cost
    total_cost = meal_cost + tip + tax
    print(round(int(total_cost)))

上面的代码适用于系统给出的大多数输入,期望 1 是

10.25

17

5

我的代码打印了 12 但预期的输出是 13,我唯一的猜测是预期的输出不正确

【问题讨论】:

  • 对于输入(10.25,17,5),总成本为12.504。当你应用 int 时,它会给你整数 12。这就是为什么你没有得到 13 作为结果。
  • 你可以在这里找到解释:stackoverflow.com/a/31818069/14280520

标签: python


【解决方案1】:

问题在于函数定义的最后一行。当您使用int(total_cost) 时,该值将被截断以解析为整数。你应该做的是四舍五入而不像这样截断为整数:

print(round(total_cost))

注意,round 也返回一个整数,但舍入而不是截断。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 2014-03-28
    • 1970-01-01
    • 2011-06-04
    • 1970-01-01
    • 2011-05-02
    • 2019-12-21
    相关资源
    最近更新 更多