带有while功能的无限循环,我无法调试它

时间:2016-01-28 20:37:03

标签: python python-2.7 while-loop infinite-loop

这是我的代码(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。它不应该那样做,我不明白为什么。

显然,我是一名新程序员。这是一个类赋值,所以虽然我确信有更好的方法来实现这个结果。我需要保持这种基本格式。

有人想要把这个新秀放在正确的轨道上吗?

干杯!

1 个答案:

答案 0 :(得分:1)

您忘记在外部循环顶部将设置回0。它第一次到达12,然后永远不会重置。像这样:

while abs(testBal) > .001:
    month = 0
    testBal = balance
    ans = (high + low)/2
    while month < 12:
        ...

另请注意,您已经检查了两次余额太高。

其他评论说明:

  1. 你滥用了apr一词;你应该把它改成准确的东西。实际APR =(1 + annualInterestRate / 12)** 12
  2. 你每个月都会重新计算(1 + apr / 12);这在整个计划中都没有改变。
  3. 您的循环应为 ,而不是