编辑:下面是我根据收到的反馈/答案的工作代码。
这个问题源于我之前在使用 MIT 的开放课件学习 Python/CS 时提出的问题。--在这里查看我之前的问题--
我正在使用以下代码列出每月付款和其他内容。但是,在循环结束时,我需要给出月份支付的总金额的运行总计。
原始代码
balance = float(raw_input("Outstanding Balance: "))
interestRate = float(raw_input("Interest Rate: "))
minPayRate = float(raw_input("Minimum Monthly Payment Rate: "))
for month in xrange(1, 12+1):
interestPaid = round(interestRate / 12.0 * balance, 2)
minPayment = round(minPayRate * balance, 2)
principalPaid = round(minPayment - interestPaid, 2)
remainingBalance = round(balance - principalPaid, 2)
print 'Month: %d' % (month,)
print 'Minimum monthly payment: %.2f' % (minPayment,)
print 'Principle paid: %.2f' % (principalPaid,)
print 'Remaining balance: %.2f' % (remainingBalance,)
balance = remainingBalance
if month in xrange(12, 12+1):
print 'RESULTS'
print 'Total amount paid: '
print 'Remaining balance: %.2f' % (remainingBalance,)
问题是我无法弄清楚如何保持支付金额的总和。我尝试添加totalPaid = round(interestPaid + principalPaid, 2)
,但这只会导致一个月的总数,我似乎无法让它保持每个月的值,然后在最后将它们全部加起来以打印出来。
我也知道结果量应该是 1131.12
当通过列表知道每个值时,我发现了很多这样做的例子,但我似乎无法正确推断。
固定代码
balance = float(raw_input("Outstanding Balance: "))
interestRate = float(raw_input("Interest Rate: "))
minPayRate = float(raw_input("Minimum Monthly Payment Rate: "))
totalPaid = 0
for month in xrange(1, 12+1):
interestPaid = round(interestRate / 12.0 * balance, 2)
minPayment = round(minPayRate * balance, 2)
principalPaid = round(minPayment - interestPaid, 2)
remainingBalance = round(balance - principalPaid, 2)
totalPaid += round(minPayment, 2)
print 'Month: %d' % (month,)
print 'Minimum monthly payment: %.2f' % (minPayment,)
print 'Principle paid: %.2f' % (principalPaid,)
print 'Remaining balance: %.2f' % (remainingBalance,)
balance = remainingBalance
if month in xrange(12, 12+1):
print 'RESULTS'
print 'Total amount paid: %.2f' % (totalPaid,)
print 'Remaining balance: %.2f' % (remainingBalance,)