Python三数最大值判断代码输出异常问题排查求助
问题根源
核心问题是输入类型不匹配:Python的input()函数默认返回字符串,直接用>/>=比较时,是按字符串的字典序(ASCII字符编码值)对比,而非数值大小对比。
比如输入33和6时,字符串"33"的第一个字符'3'ASCII码为51,'6'的ASCII码为54,所以"33" < "6"会被判定为True,导致代码错误认为6是最大值。
修正方案
将输入的字符串转换为数值类型(整数用int(),浮点数用float())后再进行比较。
修正后的代码
a = int(input("Enter the first number:")) b = int(input("Enter the second number:")) c = int(input("Enter the third number:")) if a > b and a > c: print(a, "is the greatest number") elif b > c: print(b, "is the greatest number") else: print(c, "is the greatest number")
补充说明
- 若需要支持小数输入,把
int()替换为float()即可。 - 测试输入
33、33、6时,会正确输出33 is the greatest number。
内容的提问来源于stack exchange,提问作者Taseen Yasir Pritam
相关产品推荐
相关产品推荐

