带while循环的销售税计算器如何实现累计总支付金额功能
销售税计算器累计总支付额修改方案
实现累计效果只需要新增一个全局累计变量存储历史总支付额,每次计算完单商品金额后做累加即可,修改后代码如下:
rate = 0.08875 # 销售税率 cumulative_total = 0 # 累计总支付额,初始值为0 amount = 1 while amount != 0: amount = float(input("Enter item cost in dollars, 0 to quit: ")) # 输入0直接退出,不计算无效值 if amount == 0: break tax = amount * rate # 当前商品对应税费 total = amount + tax # 当前商品含税费总支付额 cumulative_total += total # 累加当前金额到累计总额 print("Tax amount on this item ==", tax) print("Total payment for this item ==", total) print("Cumulative total payment ==", cumulative_total)
改动说明
- 循环执行前初始化
cumulative_total变量,专门用来存储多轮计算的总支付额累加结果 - 新增输入为0时的终止逻辑,避免对0值做无意义的税费计算
- 每轮计算完单商品总支付额后,通过
cumulative_total += total语句完成累加 - 可选添加
round()方法限制输出的小数位数,避免浮点运算导致的超长小数显示,例如把输出改为print("Cumulative total payment ==", round(cumulative_total, 6))即可保留6位小数,和你给出的示例输出格式匹配
内容的提问来源于stack exchange,提问作者nickg
相关产品推荐
相关产品推荐

