Python 程序来计算三角形的面积(Program to find area of a triangle)

 给定一个三角形的边,任务是求出该三角形的面积。

例如: 

输入: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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值