我将如何摆脱这个无限循环?
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.")
有没有办法把用户输入的数字 cpi
加倍,这样 while cpi <= (cpi * 2)
就不会出现死循环?另外,有没有办法让用户输入浮点数,这样就不会 return Bad input
错误?非常感谢所有帮助。
您应该将给定的值保存为输入
cpi = float(cpi)
target_cpi = cpi * 2
while cpi <= target_cpi:
cpi *= 1.025
numOfYears += 1
其他人已经解释了为什么会出现无限循环:您将 cpi
与其 current 值而不是其 original[=39= 进行比较] 价值。然而,还有更多:
numOfYears
的结果独立于cpi
- 你根本不需要循环,只需要使用logarithms
因此您可以将代码更改为:
from math import ceil, log
numOfYears = ceil(log(2) / log(1.025))
根据 1.025
.
的年变化率,这给出了 任何 CPI 翻倍之前的年份
关于您的其他问题:
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?
您应该 try
转换为 float 并 break
从循环开始工作。
while True:
try:
cpi = float(input("Enter the CPI for July 2015: "))
break
except ValueError:
print("Bad input")
但正如我所说,对于您在该脚本中计算的内容,您根本不需要该数字。
##
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)
就不会出现死循环?另外,有没有办法让用户输入浮点数,这样就不会 return Bad input
错误?非常感谢所有帮助。
您应该将给定的值保存为输入
cpi = float(cpi)
target_cpi = cpi * 2
while cpi <= target_cpi:
cpi *= 1.025
numOfYears += 1
其他人已经解释了为什么会出现无限循环:您将 cpi
与其 current 值而不是其 original[=39= 进行比较] 价值。然而,还有更多:
numOfYears
的结果独立于cpi
- 你根本不需要循环,只需要使用logarithms
因此您可以将代码更改为:
from math import ceil, log
numOfYears = ceil(log(2) / log(1.025))
根据 1.025
.
关于您的其他问题:
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?
您应该 try
转换为 float 并 break
从循环开始工作。
while True:
try:
cpi = float(input("Enter the CPI for July 2015: "))
break
except ValueError:
print("Bad input")
但正如我所说,对于您在该脚本中计算的内容,您根本不需要该数字。