带有while函数的无限循环,我无法调试它
Infinite Loop with while function and I can't debug it
这是我的代码 (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。它不应该那样做,同样,我不明白为什么。
很明显,我是一名新程序员。这是一个 class 作业,所以虽然我确信有更好的方法可以实现这个结果。我需要保持这种基本格式。
有人想试一试让这个新秀走上正轨吗?
干杯!
您忘记在外循环的顶部将 月 设置回 0。它第一次达到 12,然后再也不会重置。像这样:
while abs(testBal) > .001:
month = 0
testBal = balance
ans = (high + low)/2
while month < 12:
...
另请注意,您已两次检查余额是否过高。
其他评论说明:
- 您误用了 apr 这个词;您应该将其更改为准确的内容。实际APR = (1 + annualInterestRate/12) ** 12
- 您每个月重新计算 (1 + apr / 12);这在整个程序中都不会改变。
- 你的 month 循环应该是 for,而不是 while.
这是我的代码 (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。它不应该那样做,同样,我不明白为什么。
很明显,我是一名新程序员。这是一个 class 作业,所以虽然我确信有更好的方法可以实现这个结果。我需要保持这种基本格式。
有人想试一试让这个新秀走上正轨吗?
干杯!
您忘记在外循环的顶部将 月 设置回 0。它第一次达到 12,然后再也不会重置。像这样:
while abs(testBal) > .001:
month = 0
testBal = balance
ans = (high + low)/2
while month < 12:
...
另请注意,您已两次检查余额是否过高。
其他评论说明:
- 您误用了 apr 这个词;您应该将其更改为准确的内容。实际APR = (1 + annualInterestRate/12) ** 12
- 您每个月重新计算 (1 + apr / 12);这在整个程序中都不会改变。
- 你的 month 循环应该是 for,而不是 while.