我如何摆脱这种无限循环?

时间:2015-10-11 20:58:07

标签: python while-loop infinite-loop

##
numOfYears = 0
## Ask user for the CPI
cpi = input("Enter the CPI for July 2015: ")
## If they didn't enter a digit, try again
while not cpi.isdigit():
    print("Bad input")
    cpi = input("Enter the CPI for July 2015: ")
## Convert their number to a float
cpi = float(cpi)
while cpi <= (cpi * 2):
    cpi *= 1.025
    numOfYears += 1
## Display how long it will take the CPI to double
print("Consumer prices will double in " + str(numOfYears) + " years.")

有没有办法获取用户输入的数字cpi并加倍,以便while cpi <= (cpi * 2)不会给我一个无限循环?另外,有没有办法允许用户输入浮点数,以便它不会返回Bad input错误?非常感谢所有帮助。

2 个答案:

答案 0 :(得分:6)

其他人已经解释了为什么会出现这种无限循环:您将cpi与其当前值进行比较,而不是将其与原始值进行比较。但是,还有更多:

  1. numOfYears的结果独立于cpi
  2. 您根本不需要循环,只需使用logarithms
  3. 即可

    所以你可以改变你的代码:

    from math import ceil, log
    numOfYears = ceil(log(2) / log(1.025))
    

    根据1.025的年度变化率,任何任何 CPI都会增加一倍。

    关于您的其他问题:

      

    此外,有没有办法允许用户输入浮点数,以便它不会返回“输入错误”错误?

    你应该try只要它循环就转换为浮点数和break

    while True:
        try:
            cpi = float(input("Enter the CPI for July 2015: "))
            break
        except ValueError:
            print("Bad input")
    

    但正如我所说,对于你在该剧本中计算的内容,你根本不需要这个数字。

答案 1 :(得分:2)

您应该将值donnt保存为输入

cpi = float(cpi)
target_cpi = cpi * 2
while cpi <= target_cpi:
    cpi *= 1.025
    numOfYears += 1