贷款支付计算

2024-10-03 06:20:56 发布

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

我正在学习Python,但我被卡住了。我在找贷款支付金额。我目前有:

def myMonthlyPayment(Principal, annual_r, n):
    years = n
    r = ( annual_r / 100 ) / 12
    MonthlyPayment = (Principal * (r * ( 1 + r ) ** years / (( 1 + r ) ** (years - 1))))
    return MonthlyPayment

n=(input('Please enter number of years of loan'))
annual_r=(input('Please enter the interest rate'))
Principal=(input('Please enter the amount of loan'))

但是,当我跑的时候,我会少跑一点。如果有人能指出我的错误,那就太好了。我使用的是python3.4。在


Tags: oftheprincipalinputreturndef金额enter
3条回答

我想在你最后的计算中

/ (( 1 + r ) ** (years - 1))

你的括号错了,应该是的

^{pr2}$

付款计算方面,您似乎没有正确翻译formula。除此之外,由于内置的input()函数返回字符串,因此在将值传递给期望值为数值的函数之前,您需要将它返回的任何内容转换为正确的类型。在

def myMonthlyPayment(Principal, annual_r, years):
    n = years * 12  # number of monthly payments
    r = (annual_r / 100) / 12  # decimal monthly interest rate from APR
    MonthlyPayment = (r * Principal * ((1+r) ** n)) / (((1+r) ** n) - 1)
    return MonthlyPayment

years = int(input('Please enter number of years of loan: '))
annual_r = float(input('Please enter the annual interest rate: '))
Principal = int(input('Please enter the amount of loan: '))

print('Monthly payment: {}'.format(myMonthlyPayment(Principal, annual_r, years)))

我认为正确的公式是

MonthlyPayment = (Principal * r) / (1 - (1 + r) ** (12 * years))

我清理了你的一些变量

^{pr2}$

在输入周围添加try-except块也是比较谨慎的。在

相关问题 更多 >