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! ')
额外小建议
- 可以给用户加个提示,说明APR需要输入百分比数值(比如5代表5%),避免混淆。
additionalInvesting变量你定义了但没用到,如果后续要加定期追加投资的逻辑,记得把它加入公式里哦。
内容的提问来源于stack exchange,提问作者Dannnyb
相关产品推荐
相关产品推荐

