|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
问:在这个程序中,int()为什么没法将浮点数8.7转换成8呢?输入8.7应该被int()转换为8然后再输入程序,我以为结果会是猜对了,结果报错了
猜猜我心中的数字:8.7
Traceback (most recent call last):
File "E:\课后作业\004讲新版\猜数字游戏.py", line 2, in <module>
guess=int(temp)
ValueError: invalid literal for int() with base 10: '8.7'
>>> int(8.7)
8
>>>
======================= RESTART: E:\课后作业\004讲新版\猜数字游戏.py =======================
猜猜我心中的数字:8
你怎么知道
猜对了又咋地!
game over
>>>
字符串 '8.7' 不能强制转化成整数,但是小数 8.7 可以转化成整数。
- >>> int('8.7')
- Traceback (most recent call last):
- File "<pyshell#0>", line 1, in <module>
- int('8.7')
- ValueError: invalid literal for int() with base 10: '8.7'
- >>> int(8.7)
- 8
复制代码
如果想让浮点数字符串转化成浮点数,可以使用 float() 函数:
- >>> float('8.7')
- 8.7
- >>> int(float('8.7')) # 通过 int() 函数将浮点数转化为整数
- 8
复制代码
|
-
猜数字游戏源代码
-
输入8.7报错
|