You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何计算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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 19:42:51