You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python求三个数最大值代码异常:输入100、10、20时结果错误

问题分析与解决

Hey there! Let's break down why your code is returning 20 instead of 100 when you input those values.

The root issue here is how you're handling the input values. The input() function in Python returns a string by default, not a number. So when you compare a > b where a is "100" and b is "10", you're actually doing string comparison, not numeric comparison.

String comparison works by checking characters one by one from left to right using their ASCII values. Let's see:

  • "100" vs "20": The first character of "100" is "1" (ASCII code 49), and the first character of "20" is "2" (ASCII code 50). Since 49 < 50, Python considers "100" < "20". That's why your code skips the first two conditions and hits the else clause, setting lnum to c (which is "20").

Fixing the Code

To fix this, you just need to convert each input string to an integer (or float if you need to handle decimal numbers) right when you get it:

a = int(input("Enter 1st value"))
b = int(input("Enter 2nd value"))
c = int(input("Enter 3rd value"))

if (a > b) and (a > c):
    lnum = a
elif (b > a) and (b > c):
    lnum = b
else:
    lnum = c

print("The largest number is", lnum)

If you want to support decimal inputs, replace int() with float() instead.

Now when you input 100, 10, 20, Python will compare them as actual numbers, so 100 will correctly be recognized as the largest value.

内容的提问来源于stack exchange,提问作者Sowmya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 16:47:42