【问题标题】:Finding if a triangle is right-angled or not判断一个三角形是否直角
【发布时间】:2019-05-16 01:08:40
【问题描述】:

这个基于 Python 3 的函数在给定边长 x、y 和 z 的情况下返回三角形是否为直角。我在简化条件语句时遇到问题。这个函数应该检查锐角、直角、钝角、斜角、等腰角和等边角,还是有条件可以跳过?感谢您提供任何反馈。

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))

【问题讨论】:

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


    【解决方案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)
    

    【讨论】:

    • 感谢您的帮助。我稍微改了一下代码,让读者可以理解它解决了什么:return (c**2+b**2==a**2) or (a**2+c**2==b**2) or (a**2+b**2==c**2)
    【解决方案2】:

    我建议使用勾股定理通过测试 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
    

    【讨论】:

    • 感谢您准确地测试直角三角形的有效性。
    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2014-08-01
    • 2011-10-30
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多