问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

使用C++和余弦定理计算三角形第三边

创作时间:
作者:
@小白创作中心

使用C++和余弦定理计算三角形第三边

引用
CSDN
1.
https://m.blog.csdn.net/hefeng_aspnet/article/details/144349757

给定两条边 A、B 和夹角 C,可以使用余弦定理来计算三角形的第三边。余弦定理的公式如下:

假设 a、b、c 是三角形的边,其中 c 是角 C 对面的边。则有:

c^2 = a^2 + b^2 - 2ab*cos(C)

c = sqrt(a^2 + b^2 - 2ab*cos(C))

接下来,我们通过一个C++程序来实现这个计算过程:

// CPP program to find third side of triangle using law of cosines
#include <bits/stdc++.h>
using namespace std;

// Function to calculate cos value of angle c
float cal_cos(float n)  
{  
    float accuracy = 0.0001, x1, denominator, cosx, cosval;  
    // Converting degrees to radian  
    n = n * (3.142 / 180.0);  
    x1 = 1;  
    // Maps the sum along the series  
    cosx = x1;  
    // Holds the actual value of sin(n)  
    cosval = cos(n);  
    int i = 1;  
    do {  
        denominator = 2 * i * (2 * i - 1);  
        x1 = -x1 * n * n / denominator;  
        cosx = cosx + x1;  
        i = i + 1;  
    } while (accuracy <= fabs(cosval - cosx));  
    return cosx;  
}  

// Function to find third side  
float third_side(int a, int b, float c)  
{  
    float angle = cal_cos(c);  
    return sqrt((a * a) + (b * b) - 2 * a * b * angle);  
}  

// Driver program to check the above function  
int main()  
{  
    float c = 49;  
    int a = 5, b = 8;  
    // function call  
    cout << third_side(a, b, c);  
    return 0;  
}  

运行上述程序,输出结果为:

6.04339

时间复杂度:O(log(n)),因为使用内置 sqrt 函数

辅助空间:O(1),因为我们不使用任何额外空间。

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号