初学者:为什么报错invalid literal for int() with base 10
我想设计个随意输入一个数字,四舍五入后输出整数的操作。开始这么写:
x =input("Enter an value : ")
x=int(x+0.5)
print(x)
结果:报错:
”Traceback (most recent call last):
File "C:/Users/pc/AppData/Local/Programs/Python/Python36/1.py", line 2, in <module>
x=int(x+0.5)
TypeError: must be str, not float
后来尝试把输入的值,按整数输出
x =int(input("Enter an value : "))
print(x)
结果还是报错:
Traceback (most recent call last):
File "C:/Users/pc/AppData/Local/Programs/Python/Python36/1.py", line 1, in <module>
x =int(input("Enter an value : "))
ValueError: invalid literal for int() with base 10: '2.2'
为什么呀,实在不明白???? x =input("Enter an value : ")
这里 x 得到的是一个 str 类型,所以下面应该是:
x = int(float(x) + 0.5)
页:
[1]