计算Python错误中的未来投资价值

时间:2019-03-20 14:22:04

标签: python function

所以我正在尝试解决这个问题;该图像包含一些示例输出。

Problem to solve

这是我到目前为止的代码,我不确定我要去哪里。问题在于在样本运行中未显示正确的数字。

investmentAmount=0
intr=0

   monthlyInterestRate=0

def futureInvestmentValue(investmentAmount, monthlyInterestRate, years):

    futureInvestmentValue=investmentAmount*(1+monthlyInterestRate)**years
    return futureInvestmentValue

def main():

  investmentAmount=int(input("The amount invested: "))
  intr=int(input("Annual interest rate: "))
  monthlyInterestRate=intr/1200

  print("Years Future Value")
     for yrs in range(1,31):

    FIV=futureInvestmentValue(investmentAmount,monthlyInterestRate,yrs)
      print(yrs, format(FIV, ".2f"))
 main()

1 个答案:

答案 0 :(得分:0)

您会混淆月份和年份。在代码中,尽管已将变量命名为years,但实际上您是在以月为单位计算增量。并且您可能希望将利率转换为float而不是int,以允许更大范围。

这是更正的代码(我没有更改公式):

def future_investment_value(investment_amount, monthly_interest_rate, months):
    return investment_amount * (1 + monthly_interest_rate)**months

def main():
    investment_amount = int(input("The amount invested: "))
    yearly_interest_rate = float(input("Annual interest rate: "))
    monthly_interest_rate = yearly_interest_rate / 1200

    print("Months future value")
    for months in range(1, 30*12 + 1):
        fut_val = future_investment_value(
            investment_amount, monthly_interest_rate, months)

        if months % 12 == 0:
            print('{:3d} months | {:5.1f} years ==> {:15.2f}'.format(
                months, months / 12, fut_val))

if __name__ == '__main__':
    main()

正如您在输出中看到的,在60个月(5年)时,输出是您期望的:

The amount invested: 10000
Annual interest rate: 5
Months future value
 12 months |   1.0 years ==>        10511.62
 24 months |   2.0 years ==>        11049.41
 36 months |   3.0 years ==>        11614.72
 48 months |   4.0 years ==>        12208.95
 60 months |   5.0 years ==>        12833.59
 72 months |   6.0 years ==>        13490.18
...
336 months |  28.0 years ==>        40434.22
348 months |  29.0 years ==>        42502.91
360 months |  30.0 years ==>        44677.44