【发布时间】:2016-11-02 00:03:12
【问题描述】:
这是我从 YouTube 上的 Python 编程教程从零到英雄计算抵押贷款的代码。我试图理解为什么这段代码没有给我使用其他支付计算器得到的相同答案。我知道还有其他代码可以给我正确的答案,但我正试图弄清楚这个代码有什么问题......
# M = L[i(1+i)n]/[(1+i)n-1]
#Declare and initialize the variables
monthlyPayment = 0
loanAmount = 0
interestRate = 0
numberOfPayments = 0
loanDurationInYears = 0
#Ask the user for the values needed to calculate the monthly payments
strLoanAmount = input("How much money will you borrow? ")
strInterestRate = input("What is the interest rate on the loan? ")
strLoanDurationInYears = input("How many years will it take you to pay off the loan? " )
#Convert the strings into floating numbers so we can use them in the formula
loanDurationInYears = float(strLoanDurationInYears)
loanAmount = float(strLoanAmount)
interestRate = float(strInterestRate)
#Since payments are once per month, number of payments is number of years for the loan * 12
numberOfPayments = loanDurationInYears*12
#Calculate the monthly payment based on the formula
monthlyPayment = loanAmount * interestRate * (1+ interestRate) * numberOfPayments \
/ ((1 + interestRate) * numberOfPayments -1)
#provide the result to the user
print("Your monthly payment will be " + str(monthlyPayment))
#Extra credit
print("Your monthly payment will be $%.2f" % monthlyPayment)
【问题讨论】:
-
你必须告诉它有什么问题。结果是什么?应该是什么?输入值是多少?
-
我很确定这不是正确的公式,请参阅:en.wikipedia.org/wiki/… 请注意,您不要乘以 n,而是使用 n 作为指数。此外,对于它的价值,我会非常警惕告诉您“声明和初始化”这样的 Python 变量的教程。首先,Python中没有这种东西,只有变量赋值。虽然在对变量执行某些操作之前分配一个值可能很有用,但在这种情况下,您的代码不会受到影响,您可以删除这些行并获得完全相同的结果。