006讲课后作业的问题
score = input("请输入你的成绩:")
while score != "e":
score = int(score)
if score < 60:
print("D")
elif 60 <= score < 80:
print("C")
elif 80 <= score < 90:
print("D")
elif 90 <= score <100:
print("A")
elif score == 100:
print("S")
else:
print("请输入0~100间数字")
score = input("请输入你的成绩:")
这串代码运行时,当我输入99.5这样的数值时就会报错ValueError: invalid literal for int() with base 10: '99.5'。然后我我在IDLE上试了一下,“score = input("请输入你的成绩:")”,然后输入99.5,然后“print(score)”,显示99.5,然后我“int(score)”报同样的错误,int(99.5)却没问题,有大佬可以解释一下吗 elif score < 70:
print("C")
elif score < 80:
print("B")
elif score < 90:
print("A")
else:
print("A+")
score = input("请再次输入你的成绩,或者输入'e'退出:")
print("程序结束")
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 因为int()函数只能将字符串中的非数字字符去掉,不会再进行其他的操作。你这里99.5显然不是一个整数,你可以用score = float(score) 因为你的 score变量是一个浮点数形式的字符串,所以直接用 int 进行类型转换会报 ValueError 错 这是因为 int() 函数只能将字符串转化为整数,不能转化成小数。例如,你可以 int('99') 转化为 99,但是不能 int('99.5') 转化为 99.5。如果你想要包含小数点的分数,你应该使用 float() 函数来代替 int()。例如: score = float(score)。
你可以修改成这样:
score = input("请输入你的成绩:")
while score != "e":
score = float(score)
if score < 60.0:
print("D")
elif 60.0 <= score < 80.0:
print("C")
elif 80.0 <= score < 90.0:
print("B")
elif 90.0 <= score < 100.0:
print("A")
elif score == 100.0:
print("S")
else:
print("请输入0~100间数字")
score = input("请输入你的成绩:")
还有我看到你有2个D,也给你修改了。
求最佳答案 本帖最后由 jackz007 于 2024-3-9 18:05 编辑
score = int(score) # score 既可以是字符串,也可以是数值(整型数、浮点数),但是,不允许 score 是字符串形式的字符串,也就是说 int(9.5) ok,int('9.5') 不 ok
如果你的代码想兼容浮点数,那就改为:
score = float(score) # score 既可以是字符串,也可以是数值(整型数、浮点数),没有限制 jackz007 发表于 2024-3-9 18:00
如果你的代码想兼容浮点数,那就改为:
懂了,谢谢大佬 sfqxx 发表于 2024-3-9 15:22
这是因为 int() 函数只能将字符串转化为整数,不能转化成小数。例如,你可以 int('99') 转化为 99,但是不 ...
懂了,谢谢大佬 jiujiu0109 发表于 2024-3-9 14:55
因为你的 score变量是一个浮点数形式的字符串,所以直接用 int 进行类型转换会报 ValueError 错
懂了,感谢大佬 jiujiu0109 发表于 2024-3-9 14:50
因为int()函数只能将字符串中的非数字字符去掉,不会再进行其他的操作。你这里99.5显然不是一个整数,你可 ...
明白了,谢谢大哥 captaindai 发表于 2024-3-9 21:25
懂了,谢谢大佬
不客气
页:
[1]