查找三角形是否为直角

时间:2019-05-16 01:08:41

标签: python-3.x if-statement geometry conditional conditional-statements

如果给定边长x,y和z,三角形是否为直角,则此基于Python 3的函数将返回。我在简化条件语句时遇到问题。该功能应该检查锐角,右角,钝角,斜角肌,等腰角和等边角,还是可以跳过的条件?感谢您提供任何反馈意见。

def right_angled(x, y, z):
    """This function returns if a triangle is or isn't
    right-angled given side lengths x, y, and z."""
    p = x + y + z #triangle perimeter
    a_sym = p / 180 #triangle perimeter divided by 180 
    one = x * a_sym #angle one
    two = y * a_sym #angle two
    three = z * a_sym #angle three
    if one and two or one and three or two and three == 90:
        return "The triangle is right-angled."
    elif one and two and three == 180:
        return "The triangle is right-angled." #next conditional(s)?
    else:
        return "The triangle is not right-angled."

print(right_angled(4, 5, 6))

2 个答案:

答案 0 :(得分:1)

您的功能完全错误。

找不到角度作为边与周长的比率。

表达式if one and two不能计算总和-and是逻辑(布尔)运算符。

要确定矩形是否正确,可以利用Pythagorean theorem

def right_angled(a, b, c):
    if (a*a+b*b==c*c) or (c*c+b*b==a*a) or (a*a+c*c==b*b) :
        return "The triangle is right-angled." 
    else:
        return "The triangle is not right-angled."

或者只返回布尔结果

return (a*a+b*b==c*c) or (c*c+b*b==a*a) or (a*a+c*c==b*b)

答案 1 :(得分:0)

我建议使用勾股定理通过测试边长的3种组合来实现这一目标(a^2+b^2=c^2)。要补偿浮点不精确度,请在一个范围内进行比较:

def right_angled(a, b, c, e):
    return abs(a*a+b*b-c*c)<e or abs(b*b+c*c-a*a)<e or abs(c*c+a*a-b*b)<e

但是,范围取决于边长的比例,即小三角形比大三角形更容易通过测试。例如,边长为~0.01的三角形将通过测试,如果e=0.01。因此,使用公式(a^2+b^2)/c^2=1

对边长进行归一化比较安全(但更昂贵)
def right_angled(a, b, c, e):
    return c>0 and abs(1-(a*a+b*b)/(c*c))<e or \
           a>0 and abs(1-(b*b+c*c)/(a*a))<e or \
           b>0 and abs(1-(c*c+a*a)/(b*b))<e