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 theelseclause, settinglnumtoc(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

