我编写了一个程序来计算一个数字的阶乘,所有工作都完美无缺,但是当测试我输入一个浮点数时崩溃了。 我的目标是接受浮点数但不计算。由于程序将接受但返回类似“错误条目,只接受整数”之类的东西。 我尝试了多个语句但它只适用于我在语句中输入的数字。所以我想也许应该建立一些东西,可能是通过命名一些浮点数并进行某种减法。但我迷路了。 这是我迄今为止没有包含浮动语句的程序:
def main():
# take input from the user
num = int(input("Enter a number: "))
factorial = 1
if num > 100:
print("Bad entry. It should be an integer less than or equal to 100!")
print("Please try again: ")
elif num == 0:
print("The factorial of 0 is 1")
elif num < 0:
print("Bad entry. It should be an integer superior than or equal to 0!")
print("Please try again: ")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
main()
答案 0 :(得分:3)
您应该使用try / catch块,因为int('3.2')
(或任何其他浮点字符串)将引发错误。例如:
try: num = int(input('Enter a number...'))
except ValueError:
print 'We only accept integers.'
return
答案 1 :(得分:0)
正如许多人所建议的那样,你应该使用try/except
块。但是,如果您想接受"6.12"
之类的用户输入,并且只是从整数部分计算,您应该这样做:
user_in = "6.12" # or whatever the result from the input(...) call is
user_in = int(float(user_in)) # 6
int
不能对不是整数的字符串进行操作,但它可以在浮点数上运行。在字符串上调用float
将为您提供一个浮点数,并且在该浮点数上调用int
将返回整数部分。
答案 2 :(得分:-1)
def main():
# take input from the user
num = float(input("Enter a number: "))
if (num%1 != 0):
print("Bad entry, only integers are accepted.")
return
num = int(num)
factorial = 1
if num > 100:
print("Bad entry. It should be an integer less than or equal to 100!")
print("Please try again: ")
elif num == 0:
print("The factorial of 0 is 1")
elif num < 0:
print("Bad entry. It should be an integer superior than or equal to 0!")
print("Please try again: ")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
main()