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

2024-06-16 10:50:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做MITx 6.00.01x课程,我在第三道题的第二道题上,我卡住了。 我的代码:

    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,但是当我到达末尾的行,该行更改了上界值或下界值,然后再次启动循环后,下界值和上界值将重置为循环外的值。有人知道怎么防止吗?你知道吗


Tags: 代码for课程balancewhileroundupperboundannualinterestrate