0

我正在学习 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)
4

1 回答 1

0

您必须更改条件,好像 unpaidBalance > 0.01:lowerRepayment = repayment elif unpaidBalance < -0.01:upperRepayment = repayment 2.当 unpaidBalance 介于 -0.01 和 0.01 之间时,使循环结束

于 2014-03-29T06:01:07.147 回答