我正在修读课程6.00.1x计算机科学与编程简介。我被要求提出一个计划,计算一年内偿还信用卡余额所需的最低还款额。为此,我需要使用二分法。
我已经提出了这段代码(请参见下文)。当我运行代码时,我得到29591.55作为答案;但是,我打算得到29157.09。
任何人都可以帮助我解决我出错的地方吗?
balance = 320000
annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate/12.0
lowerRepayment = balance/12
upperRepayment = (balance * (1 + monthlyInterestRate)**12)/12
repayment = (lowerRepayment + upperRepayment)/2
unpaidBalance = balance
while unpaidBalance >= 0:
repayment = round(((lowerRepayment + upperRepayment)/2), 2)
unpaidBalance = balance
numberOfRepayments = 0
while numberOfRepayments < 12 and unpaidBalance >= 0:
numberOfRepayments += 1
monthlyUnpaidBalance = unpaidBalance - repayment
increment = monthlyUnpaidBalance * monthlyInterestRate
unpaidBalance = monthlyUnpaidBalance + increment
if unpaidBalance < -0.01:
lowerRepayment = repayment
elif unpaidBalance > 0.01:
upperRepayment = repayment
print 'Lowest Payment: ' + str(repayment)
答案 0 :(得分:0)
你必须改变条件 如果unpaidBalance&gt; 0.01: lowerRepayment =还款 elif unpaidBalance&lt; -0.01: upperRepayment =还款 2.当unpaidBalance介于-0.01和0.01之间时,使你的循环结束