使用二分查找工作來解決信用卡付款問題的答案。我認爲我堅如磐石(儘管我確定是基本的)代碼,它適用於示例輸入,但檢查返回的是無限循環。我已經嘗試了大約20種不同的平衡輸入,並且所有的輸入都恢復正確,直到插入Balance = 2000,然後它拋出了無限循環。我無法弄清楚爲什麼。任何幫助,非常感謝這裏是我的代碼:獲取某些輸入的無限循環
balance = 2000
annualInterestRate = .18
monthlyInterestRate = annualInterestRate/12.0
lower_bound = balance/12.0
upper_bound = (balance * (1 + monthlyInterestRate) ** 12)/12.0
monthly_payment = (lower_bound + upper_bound)/2.0
new_balance = balance
while new_balance != 0:
monthly_payment = (lower_bound + upper_bound)/2.0
new_balance = balance
month = 0
while month < 12 and new_balance != 0:
month += 1
new_balance = new_balance - monthly_payment
new_balance = new_balance + (new_balance * monthlyInterestRate)
new_balance = round(new_balance,2)
if new_balance < 0:
upper_bound = monthly_payment
else:
lower_bound = monthly_payment
print "Lowest Payment:", round(monthly_payment,2)