这是我的代码(Python 2.7)
##Pay off a credit card in one year. Find a monthly payment using bisection search.
balance = 1234
annualInterestRate = .2
apr = annualInterestRate
month = 0
high = (balance * (1+apr))/12
low = balance / 12
testBal = balance
ans = (high + low)/2
while abs(testBal) > .001:
testBal = balance
ans = (high + low)/2
while month < 12:
testBal = (testBal - ans) * (1 + apr / 12)
month += 1
print month, testBal , ans
if testBal < 0: #payment too high
high = ans
elif testBal > 0: #payment too low
low = ans
if testBal < 0:
high = ans
print ans
我正在使用嵌套的while函数。月份计数器有效,但在第一个循环之后,它会挂在某个地方,我不知道为什么。
我能找到的一件事是低和高变量都改为ans。它不应该那样做,我不明白为什么。
显然,我是一名新程序员。这是一个类赋值,所以虽然我确信有更好的方法来实现这个结果。我需要保持这种基本格式。有人想要把这个新秀放在正确的轨道上吗?
干杯!
答案 0 :(得分:1)
您忘记在外部循环顶部将月设置回0。它第一次到达12,然后永远不会重置。像这样:
while abs(testBal) > .001:
month = 0
testBal = balance
ans = (high + low)/2
while month < 12:
...
另请注意,您已经检查了两次余额太高。
其他评论说明: