c++ 程序来计算三角形的面积(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 

下面是上述方法的实现:

// C++ Program to find the area  
// of triangle  
#include <bits/stdc++.h> 
using namespace std; 
  
float findArea(float a, float b, float c)  
{  
    // Length of sides must be positive  
    // and sum of any two sides  
    // must be smaller than third side.  
    if (a < 0 || b < 0 || c < 0 ||  
       (a + b <= c) || a + c <= b ||  
                       b + c <= a)  
    {  
        cout << "Not a valid triangle";  
        exit(0);  
    }  
    float s = (a + b + c) / 2;  
    return sqrt(s * (s - a) *  
                    (s - b) * (s - c));  
}  
  
// Driver Code 
int main()  
{  
    float a = 3.0;  
    float b = 4.0;  
    float c = 5.0;  
  
    cout << "Area is " << findArea(a, b, c);  
    return 0;  
}  
  
// This code is contributed  
// by rathbhupendra 

输出

面积为 6

时间复杂度: O(log 2 n)

辅助空间: O(1),因为没有占用额外空间。

给定一个三角形顶点的坐标,任务是找到该三角形的面积。

方法:如果给定三个角的坐标,我们可以对下面的区域  应用鞋带公式。

// C++ program to evaluate area of a polygon using 
// shoelace formula 
#include <bits/stdc++.h> 
using namespace std; 
   
// (X[i], Y[i]) are coordinates of i'th point. 
double polygonArea(double X[], double Y[], int n) 

    // Initialize area 
    double area = 0.0; 
   
    // Calculate value of shoelace formula 
    int j = n - 1; 
    for (int i = 0; i < n; i++) 
    { 
        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 
int main() 

    double X[] = {0, 2, 4}; 
    double Y[] = {1, 3, 7}; 
   
    int n = sizeof(X)/sizeof(X[0]); 
   
    cout << polygonArea(X, Y, n); 

输出
2

时间复杂度: O(n)

辅助空间: O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

csdn_aspnet

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值