<p>代码中有一些问题,通过使用下面的代码执行diff可以很容易地看到。你知道吗</p>
<ol>
<li>calculateValues:在循环中运行,并在第一次迭代时返回结果</li>
<li>printPayments调用calculateValues,但不获取结果(这就是为什么一次又一次地打印同一行的原因)</li>
<li>printPayments也在一个循环中打印-这意味着有一个循环是不需要的</li>
<li>main()调用calculateValues,然后调用printPayments,这意味着两个for循环被调用的次数太多,没有保存结果</li>
</ol>
<p>以下是固定代码:</p>
<pre><code>import math
import sys
def calculateValues(monthlyRate, loanAmt, numYears):
monthlyRate = monthlyRate / 100
monthlyPayment = loanAmt * monthlyRate / (1 - math.pow(1 / (1 + monthlyRate), numYears * 12))
totalPayment = monthlyPayment * numYears * 12
return monthlyRate, monthlyPayment, totalPayment
def printPayments(loanAmt, numYears):
print("Rate Monthly Payment Total Payment")
for monthlyRate in range (4, 9):
monthlyRate, monthlyPayment, totalPayment = calculateValues(monthlyRate, loanAmt, numYears)
print("{0}% ${1:0.2f} ${2:0.2f}".format(int(monthlyRate*100, monthlyPayment, totalPayment))
def repeat():
question = str(input("Would you like to create a new table? (Enter y for yes): "))
if (question == "y"):
main()
else:
sys.exit()
def getPositiveFloat():
loanAmt = int(input("Enter the amount of the loan: "))
numYears = int(input("Enter the number of years: "))
if (loanAmt < 0) or (numYears < 0):
print("Please enter a positive number for both questions")
main()
return loanAmt, numYears
def main():
loanAmt, numYears = getPositiveFloat()
printPayments(loanAmt, numYears)
repeat()
main()
</code></pre>
<p><strong>输出:</strong></p>
<pre><code>Enter the amount of the loan: 100
Enter the number of years: 20
Rate Monthly Payment Total Payment
4% $4.00 $960.08
5% $5.00 $1200.01
6% $6.00 $1440.00
7% $7.00 $1680.00
8% $8.00 $1920.00
Would you like to create a new table? (Enter y for yes):
</code></pre>
<p>我认为你计算利息的方法有问题:</p>
<pre><code>monthlyPayment = loanAmt * monthlyRate / (1 - math.pow(1 / (1 + monthlyRate), numYears * 12))
</code></pre>
<p>但这部分我让你自己解决;)</p>