给定两条边 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),因为我们不使用任何额外空间。
如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。