给定一个三角形的边,任务是求出该三角形的面积。
例如:
输入:a = 5, b = 7, c = 8
输出:三角形面积为 17.320508
输入:a = 3, b = 4, c = 5
输出:三角形面积为 6.000000
方法:可以使用以下公式简单地计算 三角形的面积。
其中 a、b 和 c 是三角形边长,
s = (a+b+c)/2
下面是上述方法的实现:
# Python Program to find the area
# of triangle
# Length of sides must be positive
# and sum of any two sides
def findArea(a,b,c):
# must be smaller than third side.
if (a < 0 or b < 0 or c < 0 or (a+b <= c) or (a+c <=b) or (b+c <=a) ):
print('Not a valid triangle')
return
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
print('Area of a triangle is %f' %area)
# Initialize first side of triangle
a = 3.0
# Initialize second side of triangle
b = 4.0
# Initialize Third side of triangle
c = 5.0
findArea(a,b,c)
# This code is contributed by Shariq Raza
输出
面积为 6
时间复杂度: O(log 2 n)
辅助空间: O(1),因为没有占用额外空间。
给定一个三角形顶点的坐标,任务是找到该三角形的面积。
方法:如果给定三个角的坐标,我们可以对下面的区域 应用鞋带公式。
# Python 3 program to evaluate
# area of a polygon using
# shoelace formula
# (X[i], Y[i]) are coordinates of i'th point.
def polygonArea(X,Y, n) :
# Initialize area
area = 0.0
# Calculate value of shoelace formula
j = n - 1
for i in range( 0, n) :
area = area + (X[j] + X[i]) * (Y[j] - Y[i])
j = i # j is previous vertex to i
# Return absolute value
return abs(area // 2.0)
# Driver program to test above function
X = [0, 2, 4]
Y = [1, 3, 7]
n = len(X)
print(polygonArea(X, Y, n))
# This code is contributed
# by Nikita Tiwari.
输出
2
时间复杂度: O(n)
辅助空间: O(1)