Как мне заставить эту формулу работать и поместить функцию return в оператор print, чтобы она просто выводила денежную стоимость? - PullRequest
0 голосов
/ 23 января 2020
def compound_interest(P, r, n, Y):
    '''
    Computes the future value of investment after Y years

    P: initial investment principal
    r: the annual interest rate
    n: the number of times per year interest will be compounded
    Y: the number of years over which to invest

    P = float(input("Enter your starting principal ($): "))
    r = float(input("Enter the annual interest rate (value between 0 and 1): "))
    n = float(input("Enter the number of times per year to compound interest: "))
    Y = float(input("Enter the number of years over which to invest: "))

    returns: the future value of investment
    '''
    compound_interest = ((P)((1+(r/n))**(ny)))
    print("After 10 year (s), you will have", "$" + str(compound_interest))
    return compound_interest

1 Ответ

1 голос
/ 23 января 2020

Вот решение вашей проблемы:

import math

def compound_interest():

    P = float(input("Enter your starting principal ($): "))
    r = float(input("Enter the annual interest rate (value between 0 and 1): "))
    n = float(input("Enter the number of times per year to compound interest: "))
    Y = float(input("Enter the number of years over which to invest: "))
    cpd_interest = P * math.pow(r+1, n * Y)
    print("After {} year (s), you will have {} $".format(Y, cpd_interest))
    return cpd_interest

compound_interest()

Я удалил параметры, которые вы задаете в своей функции, потому что они вам не нужны, если вы запрашиваете их как input() из пользователь.

Я также улучшил ваши расчеты: когда вы хотите рассчитать процент, он должен быть начальным принципалом * (процентный процент +1 к степени (число лет умноженное на число раз в год)). Для этого я использовал функцию math.pow (), и вы можете увидеть здесь , как она работает точно.

Я переименовал имя переменной с составного_интереса в cpd_interest, так как было бы плохой идеей иметь имена переменных с тем же именем, что и у вашей функции.

Я также переписал ваш оператор печати и использовал поле замены правильно отформатировать вложенные годы и интерес. Вы не можете вернуться внутрь оператора print, возвращение - это всегда последнее, что делает функция (если она ничего не возвращает).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...