带while函数的无限循环,我无法调试

2024-05-23 16:59:27 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码(Python2.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,它不应该这样做,我也不明白为什么。你知道吗

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

有人想尝试让这个新人走上正轨吗?你知道吗

干杯!你知道吗


Tags: 代码ifpaymentpayaprlowtooprint
1条回答
网友
1楼 · 发布于 2024-05-23 16:59:27

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

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

还要注意,您已经检查了两次余额是否过高。你知道吗


其他审核说明:

  1. 你误用了apr这个词,你应该把它改成准确的词。实际APR=(1+年利率/12)**12
  2. 您每月重新计算(1+apr/12);这在整个程序中不会改变。你知道吗
  3. 你的循环应该是for,而不是while。你知道吗

相关问题 更多 >