三角不等式
问题描述:
我必须编写一个程序,该程序需要用户输入三角形的边,并打印它是否为直角三角形以及该区域是什么。我的任务还要求我们确保没有任何一方长于其他双方的总和。我试图弄清楚如何让我的代码不会比其他双方的总和长得多,并且提示用户重新开始,但我不知所措。我也遇到了一个问题,当我的程序运行时,它打印出none,我认为它与我的def right_tri函数有关,但我不确定为什么它会这样做。三角不等式
这是我的代码任何帮助将不胜感激!
def area(a, b, c):
s = (a + b + c)/2
area = (s*(s-a)*(s-b)*(s-c)) **0.5
return format(area, '.2f')
def right_tri(a, b, c):
if (b**2 + c**2 == a**2):
print('Is a right triangle')
else:
print('Is not a right triangle')
def main() :
a = int(input('Enter longest side of the triangle'))
b = int(input('Enter the second side of the triangle'))
c = int(input('Enter the thrid side of the triangle'))
print('Area is:', triangle.area(a, b, c))
print(triangle.right_tri(a, b, c))
print(is_sum(a, b, c))
def is_sum(a, b, c):
if (a > b + c) or (b > a + c) or (c > a + b):
print ('One side is longer than the sum of the other two sides')
else:
return True
main()
答
假设你的代码的缩进是正确的(如蟒蛇依赖于它)以下应该是right_tri
实施,
def right_tri(a, b, c):
if ((b**2 + c**2 == a**2) || (a**2 + c**2 == b**2) || (b**2 + a**2 == c**2)):
print('Is a right triangle')
else:
print('Is not a right triangle')
原因多个条件是因为,你永远不知道,如果用户正在给斜边a
或b
或c
。
答
在right_tri功能,你需要使用一个return语句,就像
def right_tri(a, b, c):
if (b**2 + c**2 == a**2):
return 'Is a right triangle'
else:
return 'Is not a right triangle'
对于任何一个三角形**这是不可能的一边是长于其他双方**的总和!绝对没有必要测试这种情况。 –