【问题标题】:Infinite Loop with while function and I can't debug it [duplicate]带有while函数的无限循环,我无法调试它[重复]
【发布时间】:2016-05-06 10:06:41
【问题描述】:

这是我的代码 (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 函数。月份计数器有效,但在第一个循环之后,它在某个地方挂断了,我不知道为什么。

我能够找到的一件事是变量 low 和 high 都更改为 ans。它不应该那样做,再说一遍,我不明白为什么。

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

有人想尝试让这位新秀走上正轨吗?

干杯!

【问题讨论】:

  • 在第一次循环循环后,您永远不会将月份重置为 0
  • 问题已解决。谢谢你们。
  • 我不认为这是重复的。较旧的问题存在同源问题(不更改二等分循环的控制变量),但不是同一个问题。 OP 得到了 that 部分正确,但错过了重新初始化计算循环的控制变量。

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


【解决方案1】:

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

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

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


其他评论说明:

  1. 您误用了 apr 一词;您应该将其更改为准确的内容。实际年利率 = (1 + 年利率/12) ** 12
  2. 您每月重新计算 (1 + apr / 12);这在整个计划中都不会改变。
  3. 您的 month 循环应该是 for,而不是 while

【讨论】:

  • 很高兴能提供帮助。请记住“接受”您最喜欢的答案,以便 SO 可以正确地退出问题。
  • [脸红] 抱歉——这是我的标准文本。我看到我是 only 的答案。 :-) 尽管如此,请做一些适当的事情来防止问题挂在“开放”状态。
猜你喜欢
  • 2017-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-08
  • 1970-01-01
  • 2020-03-17
  • 2021-11-26
  • 2015-11-01
相关资源
最近更新 更多