将小数输入转换为 int 时出错

Error when converting fractional input to int

在我的阶乘计算程序中,我从用户那里得到一个数字

n=float(input("n=")) #sign

我想更改它,以便将数字转换为整数而不是浮点数:

n=int(input("n=")) #sign

但是当我输入像“4.5”这样的浮点数时,这不起作用。错误代码为:

Traceback (most recent call last):
  File "C:\Python33\factorial of n natural numbers.py", line 5, in <module>
    n=int(input("n="))
ValueError: invalid literal for int() with base 10: '4.5'

自从我决定输入浮点数后,我已经将整数转换为浮点数,但看起来它还没有被转换或什么...

该程序在第一个版本上仍然可以运行,但是那里有什么问题?这些转化之间有什么区别?

问题是 input() 函数 returns 一个字符串对象:

>>> n = input("n = ")
n = 4.5

>>> x
>>> '4.5'
>>> type(n)
<class 'str'>

作为documentation states, when you don´t pass a string instance representing a so called integer literal to Pythons int()函数,你会得到一个ValueError

>>> int(n)
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: '4.5'

为避免这种情况,您可以捕获此错误或先将字符串转换为浮点数(使用 float()——因此数字类型并不重要——然后转换为 int :

>>> int(float(n))
    4

希望这对您有所帮助:)