【发布时间】: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