用python计算未来投资价值

2024-09-22 16:30:27 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试图解决这个问题;图像包含一些示例输出。你知道吗

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()

Tags: 代码图像示例inputmaindefintprint
1条回答
网友
1楼 · 发布于 2024-09-22 16:30:27

你年复一年的困惑。在您的代码中,您实际上是在以月为单位计算增量,尽管已经命名了变量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

相关问题 更多 >