Python收银台实验:折扣后价与总价计算错误排查
Python收银台程序计算偏差修复
核心错误点
代码输出结果和预期不符,是以下逻辑错误叠加导致的:
- 会员折扣计算逻辑完全写反:你写的
cost = cost_before * 0.10 - cost_before * (-1)等价于cost = cost_before * 1.1,是在第二件半价的基础上涨价10%,而会员规则是额外减10%,正确计算应该乘以0.9,这是样例折扣价算出27.5而非22.5的核心原因。 - 会员身份判断覆盖不全:代码仅识别小写输入
y,如果用户输入大写Y,会直接跳过所有折扣、总价计算分支,无对应输出。 - 冗余逻辑过多易出错:你写了4组重复分支对比两个商品价格,很容易写反判断条件,实际上用内置函数
min()、max()可以一步算出第二件半价的金额,不需要多层if嵌套。 - 输出格式不符合要求:额外加了样例没有的
$符号,且等号两侧的空格和样例规范不一致。
修正后代码
product1 = float(input('Enter price of the first item: ')) product2 = float(input('Enter price of the second item: ')) club = input('Does customer have a club card? (Y/N): ') tax = float(input('Enter tax rate, e.g. 5.5 for 5.5% tax: ')) # 计算无折扣无税的基础总价 base_price = product1 + product2 # 计算第二件半价优惠金额:价格更低的商品算半价,高的算全价 half_promo_price = min(product1, product2) * 0.5 + max(product1, product2) # 叠加会员10%折扣 if club.strip().lower() == 'y': discount_price = half_promo_price * 0.9 else: discount_price = half_promo_price # 叠加税费计算最终应付金额 total_price = discount_price * (1 + tax / 100) # 按要求格式输出,保留2位小数 print(f'Base price = {base_price:.2f}') print(f'Price after discounts = {discount_price:.2f}') print(f'Total price = {total_price:.2f}')
运行验证
用参考样例输入运行,输出完全匹配预期:
Enter price of the first item: 10 Enter price of the second item: 20 Does customer have a club card? (Y/N): y Enter tax rate, e.g. 5.5 for 5.5% tax: 8.25 Base price = 30.00 Price after discounts = 22.50 Total price = 24.36
内容的提问来源于stack exchange,提问作者Andressa Trajano
相关产品推荐
相关产品推荐

