Python三角形三边长

题目:写一个程序,判断用户输入的三个整数(表示三边长)是否能构成一个三角形。
要求:如果不能则抛出异常,显示异常信息 “a,b,c不能构成三角形”;
          如果输入的边长中有负数,显示异常信息“三条边不能为负数”;
          如果可以构成则显示三角形的三个边长。

try:
    a = int(input("请输入第一条边的长度:"))
    b = int(input("请输入第二条边的长度:"))
    c = int(input("请输入第三条边的长度:"))

    if a <= 0 or b <= 0 or c <= 0:
        raise ValueError("三条边不能为负数")

    if a + b <= c or a + c <= b or b + c <= a:
        raise ValueError("%d,%d,%d不能构成三角形" % (a, b, c))

    print("这是一个三角形,三条边长为:%d,%d,%d" % (a, b, c))

except ValueError as e:
    print("输入有误:", e)


a = int(input("请输入第一条边的长度:"))
b = int(input("请输入第二条边的长度:"))
c = int(input("请输入第三条边的长度:"))
if a<0 or b <0 or c<0:
    print("三条边不能为负数")
elif a + b > c and a + c > b and b + c > a:
    print("这三条边可以构成三角形")
    print("这三条边的长度分别为:", a, b, c)
else:
    print("a,b,c不能构成三角形")
  • 你可以参考下这个问题的回答, 看看是否对你有帮助, 链接: https://ask.csdn.net/questions/7663550
  • 你也可以参考下这篇文章:Python编写程序求解一元二次方程,打印九九乘法表,判断三条边是否可以构成三角形,并求三角形面积
  • 除此之外, 这篇博客: python 小练习中的 依次输入三角形的三边长,判断能否生成一个直角三角形。 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • flag = True
    while flag:
        i = 1
        triangle = []
    
        # input 3 integers by loop
        while i <= 3:
            x = input(f"Please enter {i} integers:")
            # is a integer?
            try:
                x = int(x)
            except ValueError as e:
                print("Input is not integer, please retry")
                continue
            # is a positive?
            if x <= 0:
                print("Please enter a positive number")
                continue
            else:
                triangle.append(x)
                i += 1
    
        # sorting list
        triangle.sort()
    
        # a+b>c?
        if (triangle[0] + triangle[1] > triangle[2]) \
                and (triangle[1] + triangle[2] > triangle[0]) \
                and (triangle[2] + triangle[0] > triangle[1]):
            print("The three line can be made up a triangle")
            # a=b? b=c? a=c?
            if triangle[0] == triangle[1] or triangle[1] == triangle[2] or triangle[0] == triangle[2] == triangle[0]:
                print("This is a Isosceles triangle")
            # a*a+b*b=c*c?
            if triangle[0] ** 2 + triangle[1] ** 2 == triangle[2] ** 2:
                print("This is a Right triangle")
        else:
            print("The three line can NOT be made up a triangle")
        print("Please input 'q' to quit or any key to continue")
        
        #quit
        if input() is 'q':
            flag = False
    
  • 您还可以看一下 刘顺祥老师的Python数据分析与挖掘课程中的 一个好汉三个帮,聚类分析带你拉帮结派(一)小节, 巩固相关知识点
  • 以下回答由chatgpt基于相关博客总结生成:
    #判断能否构成三角形并输出三角形边长
    a,b,c=map(int,input().split())
    if a<=0 or b<=0 or c<=0:
        raise Exception("三条边不能为负数")
    elif a+b>c and a+c>b and b+c>a:
        print(a,b,c)
    else:
        raise Exception("{} {} {} 不能构成三角形".format(a,b,c))