Python三角形法则函数代码异常排查:逻辑正确但输出错误
Why Your Triangle Check Isn't Working (And How to Fix It)
Ah, I spot the key issue here — you're performing comparisons on string values instead of numeric ones, which leads to totally unexpected results!
The Root Cause
When you pull arguments from sys.argv, they’re always returned as strings. So when you do something like x < y + z, you’re not adding numbers — you’re concatenating strings and then doing lexicographical (dictionary-style) comparison, not numeric comparison.
For example:
- If you run your script with
10 2 3,y + zbecomes"2"+"3" = "23". - Lex order says
"10" < "23"isTrue, but numerically 10 is not less than 2+3=5. This would incorrectly returnTruefor sides that can’t form a triangle at all.
The Fix
You need to convert the command-line arguments to numeric types (either int for whole numbers or float if you want to support decimal lengths) before passing them to your areTriangular function.
Here’s the corrected code:
import sys def areTriangular(x,y,z): if x<y+z and y<x+z and z<x+y: return True else: return False # Convert arguments to integers (swap to float for decimal support) try: a = int(sys.argv[1]) b = int(sys.argv[2]) c = int(sys.argv[3]) except ValueError: print("Error: Please enter valid numeric values for the triangle sides.") sys.exit(1) m = areTriangular(a,b,c) print(m)
Extra Notes
- I added a
try-exceptblock to handle cases where someone might pass non-numeric inputs (like letters), which would crash the script otherwise. - If you need to support decimal side lengths (e.g., 2.5, 3.7), just replace
intwithfloatin the conversion lines. - Your core triangle logic is actually solid once you’re using numeric values — the triangle inequality check works exactly as intended when x, y, z are numbers.
内容的提问来源于stack exchange,提问作者bkk
相关产品推荐
相关产品推荐

