简体   繁体   English

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

[英]How would I get rid of this 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.")

Is there a way to take the number that the user inputs cpi and double it so that while cpi <= (cpi * 2) doesn't give me an infinite loop? 有没有一种方法可以将用户输入的cpi乘以两倍,以便while cpi <= (cpi * 2)不会给我无限循环? Also, is there a way to allow the user to input a floating point number so that it doesn't return the Bad input error? 此外,是否有一种方法允许用户输入浮点数,以使其不返回Bad input错误? All help is much appreciated. 非常感谢所有帮助。

Others have already explained why you get that infinite loop: You compare cpi to its current value instead of its original value. 其他人已经解释了为什么会出现无限循环:将cpi与它的当前值而不是其原始值进行比较。 However, there's more: 但是,还有更多:

  1. The result of numOfYears is independent of cpi numOfYears的结果独立于cpi
  2. You do not need a loop at all, just use logarithms 您根本不需要循环,只需使用对数

So you could just change your code to this: 因此,您可以将代码更改为此:

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

This gives you the years until any CPI has doubled given the annual rate of change of 1.025 . 在给定的年度变化率1.025这将为您提供年数,直到任何 CPI翻番。


About your other question: 关于您的其他问题:

Also, is there a way to allow the user to input a floating point number so that it doesn't return the 'Bad input' error? 另外,是否有一种方法允许用户输入浮点数,以使其不返回“错误输入”错误?

You should just try to convert to float and break from the loop as soon as it works. 您应该try立即将其转换为float并从循环中break

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

But as I said, for what you are calculating in that script, you do not need that number at all. 但是正如我所说,对于您在该脚本中计算的内容,您根本不需要该数字。

You should save the value givent as an input 您应该将给定的值保存为输入

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM