c++ 使用余弦定理寻找三角形第三边的程序(Program to find third side of triangle using law of cosines)

给定两条边 A、B 和角 C。利用余弦定理求出三角形的第三边。
示例: 

输入:a = 5,b = 8,c = 49

输出:6.04339

具体来说,当你知道三角形两条边的长度和中间的角度时,余弦定理可以用来求出三角形第三边的长度。参见此处了解如何求余弦值。 

假设 a、b、c 是三角形的边,其中 c 是角 C 对面的边。然后, 

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

c = sqrt(a^2 + b^2 - 2*a*b*cos(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),因为我们不使用任何额外空间。

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值