【发布时间】:2017-06-17 21:57:55
【问题描述】:
我想使用二等分搜索来找出每月需要支付多少才能在 12 个月内支付用户输入的全部余额。然而,我写的这段代码进入了无限循环,显示“低、高、月支付无限次”。我不知道哪个代码会导致这个问题,因为条件语句对我来说似乎是正确的。
initialBalance = float(raw_input('Enter the outstanding balance on your credit card'))
annualInterestrate = float(raw_input('Enter the annual credit card interest rate as a decimal'))
monthlyInterestrate = round(annualInterestrate, 2)
balance = initialBalance
while balance > 0:
numMonth = 0
balance = initialBalance
low = balance/12.0
high = (balance*(1+(annualInterestrate/12.0))**12.0)/12.0
epsilon = 0.01
monthlyPayment = round((high + low)/2.0, 2)
while abs(monthlyPayment*12.0 - initialBalance) >= epsilon:
print 'low =', low, 'high =', high, 'monthlyPayment =', round(monthlyPayment,2)
if monthlyPayment*12.0 < balance:
low = monthlyPayment
else:
high = monthlyPayment
monthlyPayment = round((high + low)/2.0, 2)
while balance > 0 and numMonth < 12:
numMonth += 1
interest = monthlyInterestrate * balance
balance -= monthlyPayment
balance += interest
balance = round(balance, 2)
print 'RESULT'
print 'monthly payment to pay off debt in 1 year:', monthlyPayment
print 'Number of months needed:', numMonth
print 'Balance:',balance
【问题讨论】:
-
循环中的第二行:
balance = initialBalance。是故意的,还是偶然的? -
我想知道通过反复试验找出近似结果的意义何在,而您可以颠倒公式并立即获得确切结果?
-
balance = initialBalance 是多余的,但我认为这不是导致此问题的原因。这是我正在研究 MIT Open 课件的问题集,它指定使用 bisect search 。
-
你能添加导致无限循环的输入吗?
-
这些是输入:
Enter the outstanding balance on your credit card: 320000Enter the annual credit card interest rate as a decimal: .2
标签: python