题目:写一个程序,判断用户输入的三个整数(表示三边长)是否能构成一个三角形。
要求:如果不能则抛出异常,显示异常信息 “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不能构成三角形")
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
#判断能否构成三角形并输出三角形边长
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))