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

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 + z becomes "2"+"3" = "23".
  • Lex order says "10" < "23" is True, but numerically 10 is not less than 2+3=5. This would incorrectly return True for 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-except block 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 int with float in 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:24:48