вычисление будущей инвестиционной стоимости в ошибке питона - PullRequest
0 голосов
/ 20 марта 2019

Итак, я пытаюсь решить эту проблему; Изображение содержит пример вывода.

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 голосов
/ 20 марта 2019

Вы путаете месяцы и год. В вашем коде вы фактически вычисляете приращения в месяцах, несмотря на то, что назвали переменную 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...