如何计算subtotal的累计总和?Python总金额计算错误求助
问题修复方案
问题根源
你代码里的核心问题是每次循环都重新给overall_total赋值为当前sub_total的两倍,完全没有累加之前所有采购项的金额,导致最终结果只是最后一项金额的两倍,而非总和。
修复后的代码
import custom def main(): each_item = True i = 0 overall_total = 0 # 初始化总金额为0 purchase = int(input('How many different items are being purchased? ')) while each_item is True: i = i + 1 desc = input('Enter description of item ' + str(i) + ' ') part = int(input('Enter part number of item ' + str(i) + ' ')) price = int(input('Enter price of item ' + str(i) + ' ')) quant = int(input('Enter the quantity for item ' + str(i) + ' ')) sub_total = custom.subtotal(desc, part, price, quant) overall_total += sub_total # 累加当前项的subtotal到总金额 print(f'Item: {desc}, Part Number: {part}, subtotal: ${sub_total:.2f}\n') if i == purchase: print(f'Your total is: ${overall_total:.2f}') break if __name__ == '__main__': main()
关键修改点
- 在循环开始前初始化
overall_total = 0,确保总金额从0开始累加 - 把错误的
overall_total = sub_total + sub_total替换为overall_total += sub_total,这行代码等价于overall_total = overall_total + sub_total,会把当前项的subtotal累加到总金额里 - 移除了未使用的
total变量,精简代码
内容的提问来源于stack exchange,提问作者Tara
相关产品推荐
相关产品推荐

