变量在while循环中不断变回原始值

时间:2016-11-08 20:50:00

标签: python

我正在做MITx 6.00.01x课程,我正处理第3个问题的第二个问题,我被卡住了。 我的代码:

    balance = 320000
    annualInterestRate = 0.2
    monthlyInterestRate = (annualInterestRate) / 12.0
    monthlyFixedPayment = 0
    empBalance = balance
    lowerBound = round((balance)/12,2)
    upperBound = (balance*(1+monthlyInterestRate)**12)/12
    monthlyFixedPayment = round( ( (lowerBound+upperBound)/2) ,2)
    while tempBalance != 0: 
        monthlyFixedPayment = round( ( (lowerBound+upperBound)/2) ,2)  
        for m in range(12) :
            tempBalance -= monthlyFixedPayment 
            tempBalance += (monthlyInterestRate)*(tempBalance)
            tempBalance = round(tempBalance,2) 
        if tempBalance > 0:
            lowerBound = round(monthlyFixedPayment,2)
            tempBalance = balance
        elif tempBalance < 0: 
            upperBound = round(monthlyFixedPayment,2)
            tempBalance = balance

    print('Lowest Payment: ' + str(round(monthlyFixedPayment,2)))

我的代码使用二分搜索来生成monthlyFixedPayment但是在我到达最后一行改变upperBound或lowerBound值然后再次开始循环之后,lowerBound和upperBound值重置为它们的值到了环。有谁知道如何防止这种情况?

0 个答案:

没有答案