67508335 发表于 2020-2-24 17:24:31

小甲鱼《零基础学python》猜数字游戏,输入小数8.7后 ,程序报错,不解求教

问:在这个程序中,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
>>>

qiuyouzhi 发表于 2020-2-24 17:28:09

别发图,发代码!!!
我要想知道错误,我还要抄一遍代码

zltzlt 发表于 2020-2-24 17:28:59

字符串 '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

67508335 发表于 2020-2-24 17:29:02

qiuyouzhi 发表于 2020-2-24 17:28
别发图,发代码!!!
我要想知道错误,我还要抄一遍代码

temp=input('猜猜我心中的数字:')
guess=int(temp)
if guess == 8:
    print('你怎么知道')
    print('猜对了又咋地!')
else :
    print('猜错啦!')
print('game over')

67508335 发表于 2020-2-24 17:29:41

代码在这里,

temp=input('猜猜我心中的数字:')
guess=int(temp)
if guess == 8:
    print('你怎么知道')
    print('猜对了又咋地!')
else :
    print('猜错啦!')
print('game over')

qiuyouzhi 发表于 2020-2-24 17:31:51

67508335 发表于 2020-2-24 17:29
temp=input('猜猜我心中的数字:')
guess=int(temp)
if guess == 8:


先用float将temp转换成浮点数再计算
代码:
temp=int(float((input('猜猜我心中的数字:')))) # 先将字符串变成浮点数,再变成整数
if temp == 8:
    print('你怎么知道')
    print('猜对了又咋地!')
else :
    print('猜错啦!')
print('game over')
页: [1]
查看完整版本: 小甲鱼《零基础学python》猜数字游戏,输入小数8.7后 ,程序报错,不解求教