Python编写dinner_calculator费用计算函数结果与预期不符求助
问题排查与修复方案
核心错误点
- 饮品成本计算逻辑错误:规则要求先对饮品原价打7折,再基于折后价计算15%的GST,你当前代码的计算逻辑为
饮品原价*0.7 + 饮品原价*0.15,是直接基于原价计算GST,不符合规则要求。 - 多余的四舍五入操作:题目明确要求函数仅返回精确浮点结果,四舍五入保留2位小数的操作由测试环节自动完成,你在返回值处提前调用
round()会导致精度偏差。
修正后代码
def dinner_calculator(meal_cost, drinks_cost): """ Calculate the cost of dinner during happy hour. Takes into consideration: - Pre-GST meal and drink costs - Happy Hour discounts - GST """ # 餐费加计15% GST meal_total = meal_cost * 1.15 # 饮品先打7折,再加计15% GST drinks_total = drinks_cost * 0.7 * 1.15 total_cost = meal_total + drinks_total # 直接返回精确结果,不提前四舍五入 return total_cost
验证示例
以餐费10元、饮品费10元为例:
- 错误代码计算结果:
10*1.15 + 10*0.7 +10*0.15 = 20 - 正确代码计算结果:
10*1.15 + 10*0.7*1.15 = 19.55
内容的提问来源于stack exchange,提问作者Sodbois
相关产品推荐
相关产品推荐

