Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将分数输入转换为整数时出错_Python_Python 3.x_Input_Numbers_Integer - Fatal编程技术网

Python 将分数输入转换为整数时出错

Python 将分数输入转换为整数时出错,python,python-3.x,input,numbers,integer,Python,Python 3.x,Input,Numbers,Integer,在我的阶乘计算程序中,我从用户那里得到一个数字 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=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'
回溯(最近一次呼叫最后一次):
文件“C:\Python33\n个自然数的阶乘.py”,第5行,在
n=int(输入(“n=”))
ValueError:基数为10的int()的文本无效:“4.5”
自从我决定输入一个浮点数后,我已经将整数转换成了浮点数,但是看起来好像它还没有被转换或者什么

这个程序仍然适用于第一个版本,但是有什么问题吗?这些转换之间有什么区别?

问题是函数返回字符串对象:

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

>>> x
>>> '4.5'
>>> type(n)
<class 'str'>
为了避免这种情况,您可以捕获此错误,或者先将字符串转换为浮点数(使用--some number type不重要--然后转换为
int

>>> int(float(n))
    4

希望这有帮助:)

您不能将任何不仅仅是数字的内容转换为int,这意味着像
4.5
这样的输入会立即引发该错误。但是,您可以将任何浮点转换为int,只要它已被转换为浮点。这是因为对浮点值调用
int()
实际上只会将浮点值截断为十进制
>>> int(float(n))
    4