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

Python新手求助:投资计算函数中公式A未生效问题

解决你的投资计算结果始终等于初始金额的问题

嘿,我一眼就揪出问题所在了——你的投资计算结果总是和初始金额一模一样,核心原因是公式里的百分比转换逻辑用错了!咱们一步步拆解:

核心错误分析

你代码里的关键公式是这行:

A = (floatP * (1.00 + (floatAPR % 1.00))** year)

这里的floatAPR % 1.00是致命bug:

  • 如果你的APR是百分比数值(比如输入5代表5%),那5 % 1.00的结果是0,这样1.00 + 0 = 1,不管多少次方都是1,最终A = floatP * 1,自然等于初始金额。
  • 就算你输入的是小数形式(比如0.05),模运算虽然能保留数值,但这个操作本身完全没必要,属于误用。

正确的百分比转换应该是除以100,把百分比数值转成小数(比如5% → 0.05)。

修正后的代码

我帮你把错误的地方改了,还顺便修正了几个拼写错误,优化了变量类型:

def calculateInvestment(budgets):
    location = -1
    counter = 0
    investmentName = input('\nEnter the name of the investment you would like to view: ')
    additionalInvesting = float(input('How much extra will be invested annually? '))
    # 年份用整数更合理,毕竟投资年份一般是整数
    year = int(input('How many years would you like to calculate out? '))
    if isinstance(budgets[counter], Investment):
        while counter < len(budgets):
            interestVariable = budgets[counter].getInvestmentApr()
            investmentName2 = budgets[counter].getInvestmentName()
            P = budgets[counter].getInvestmentAmount()
            floatP = float(P)
            floatAPR = float(interestVariable)
            if investmentName2 == investmentName:
                location = counter
                # 把模运算改成除以100,正确转换百分比到小数
                A = floatP * (1.00 + (floatAPR / 100)) ** year
                print(f'After {year} years you will have {A} from your initial investment')
                break
            counter += 1
    if location == -1:
        print('Not Found! ')

额外小建议

  1. 可以给用户加个提示,说明APR需要输入百分比数值(比如5代表5%),避免混淆。
  2. additionalInvesting变量你定义了但没用到,如果后续要加定期追加投资的逻辑,记得把它加入公式里哦。

内容的提问来源于stack exchange,提问作者Dannnyb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 20:02:30