我正在尝试使用二分搜索(二分搜索?)解决在线问题,我不确定我的代码错在哪里,我的答案与预期的答案有所不同,对我来说有点舒服。我真的很感激知道我在哪里,以及未来的指针。 我获得了年利率和初始余额。我也期望选择一个足够小的步骤,这样我就可以增加到分数。 我的代码是这样的:
startbalance = input('Balance: ')
annualInterestRate = input('annualInterestRate: ')
monthlyInterestRate = annualInterestRate / 12.0
balance = startbalance
step = 0.01
lowbound = balance / 12.0
highbound = (balance * (1 + monthlyInterestRate)**12) / 12.0
monthlyPayment = (lowbound + highbound) / 2.0
while (monthlyPayment - balance) >= step:
for month in range(0, 12):
balance -= monthlyPayment
balance = balance + ((1 + monthlyInterestRate) * balance)
if balance < 0:
highbound = monthlyPayment
balance = startbalance
elif balance > 0:
lowbound = monthlyPayment
balance = startbalance
print 'Lowest Payment: ', round(monthlyPayment, 2)
使用案例中提供的值测试我的代码,我有以下内容:
With an annual interest rate of 0.2
and a balance of 320000,
My result: 29591.88 (incorrect, the answer should be 29157.09)
With an annual interest rate of 0.18
and a balance of 999999,
My result: 91484.0 (incorrect, the answer should be 90325.03)
我想我只是有点偏离,我真的很感激一些直接的设置。
谢谢!
答案 0 :(得分:0)
修正了它(谢谢,z0k!):
startbalance = input('Balance: ')
annualInterestRate = input('annualInterestRate: ')
monthlyInterestRate = annualInterestRate / 12.0
monthlyInterestRate = annualInterestRate / 12.0
startbalance = balance
step = 0.01
lowbound = startbalance / 12.0
highbound = (startbalance * (1 + monthlyInterestRate)**12) / 12.0
monthlyPayment = (lowbound + highbound) / 2.0
while (abs(startbalance)) >= step:
startbalance = balance
for month in range(0, 12):
startbalance -= monthlyPayment
startbalance = startbalance + ((monthlyInterestRate) * startbalance)
if startbalance < 0:
highbound = monthlyPayment
if startbalance > 0:
lowbound = monthlyPayment
monthlyPayment = (lowbound + highbound) / 2.0
print 'Lowest Payment: ', round(monthlyPayment, 2)