我正在創建一個程序,它將計算出信用卡支付的最低月度支付,並給定一定的信用卡餘額和利率。回報的時間框架是12個月,每月付款必須精確到最近的一分錢,使用二分搜索。無法得到此while while循環權(python)
我能夠得到答案,問題是我無法讓我的while循環退出,一旦每月支付計算到最接近的分,所以我不得不做一個無限的while循環,有一個elif聲明在while循環的底部,爲我退出。我想知道是否有人可以找出給while循環的條件,所以它會自行退出。此外,我剛剛開始學習Python一週前,並希望得到一些關於我的代碼是好還是壞的建議。有任何想法嗎?
# random balance
balance = 999999
# random interest rate
annualInterestRate = 0.18
# assign balance to another variable that will undergo the testing
balance_tested = balance
# bounds of bisection search
low = (balance/12.0)
high = ((balance * (1 + (annualInterestRate/12.0))**12)/12.0)
# start month
month = 1
monthlyPayment = (low + high)/2.0 #Averages out the bounds to meet in the middle
while abs(balance_tested != 0): #While loop that I can't get right, just made it to run infinitely
balance_tested = balance #Resets balance being tested back to original balance
monthlyPayment = (low + high)/2.0 #Bisection search recalculates
month = 1 #Month reset back to 1
while month <= 12: #Loops through all 12 months with the payments being made and interested getting added
balance_tested = (balance_tested - monthlyPayment)
balance_tested += (balance_tested * (annualInterestRate/12))
month += 1
print "Balance Remaining: %.20f" % balance_tested
if balance_tested < 0: #If the bisection search guesses to high, decreases the high bound
high = monthlyPayment
elif balance_tested <= 0.01: #Conditional statement that stops the testing if the balance gets paid off to the cent
break
else: #If bisection search guesses to low, increases low bound
low = monthlyPayment
print "Monthly Payment: %.2f" % monthlyPayment
print "Lowest Payment: %.2f" % monthlyPayment
你必須使用bisect?分析答案是可能的。 –
但是......你不是已經有這個條件嗎?只要'while balance_tested <= 0.01:' – yuvi
不得不使用平分線,因爲這個特殊的問題要求我 – electronicaneer