给定三角形在二维平面上所有三个顶点的坐标,任务是找到所有三个角度。
示例:
输入:A = (0, 0),
B = (0, 1),
C = (1, 0)
输出:90, 45, 45
为了解决这个问题,我们使用下面的余弦定律。
c^2 = a^2 + b^2 - 2(a)(b)(cos beta)
重新安排后
beta = acos( ( a^2 + b^2 - c^2 ) / (2ab) )
在三角学中,余弦定律(也称为余弦公式或余弦规则)将三角形边的长度与其某个角的余弦联系起来。
首先,计算所有边的长度。然后应用上述公式得到所有角度的弧度。然后将角度从弧度转换为度数。
以下是上述步骤的实施:
// Code to find all three angles
// of a triangle given coordinate
// of all three vertices
#include <iostream>
#include <utility> // for pair
#include <cmath> // for math functions
using namespace std;
#define PI 3.1415926535
// returns square of distance b/w two points
int lengthSquare(pair<int,int> X, pair<int,int> Y)
{
int xDiff = X.first - Y.first;
int yDiff = X.second - Y.second;
return xDiff*xDiff + yDiff*yDiff;
}
void printAngle(pair<int,int> A, pair<int,int> B,
pair<int,int> C)
{
// Square of lengths be a2, b2, c2
int a2 = lengthSquare(B,C);
int b2 = lengthSquare(A,C);
int c2 = lengthSquare(A,B);
// length of sides be a, b, c
float a = sqrt(a2);
float b = sqrt(b2);
float c = sqrt(c2);
// From Cosine law
float alpha = acos((b2 + c2 - a2)/(2*b*c));
float beta = acos((a2 + c2 - b2)/(2*a*c));
float gamma = acos((a2 + b2 - c2)/(2*a*b));
// Converting to degree
alpha = alpha * 180 / PI;
beta = beta * 180 / PI;
gamma = gamma * 180 / PI;
// printing all the angles
cout << "alpha : " << alpha << endl;
cout << "beta : " << beta << endl;
cout << "gamma : " << gamma << endl;
}
// Driver code
int main()
{
pair<int,int> A = make_pair(0,0);
pair<int,int> B = make_pair(0,1);
pair<int,int> C = make_pair(1,0);
printAngle(A,B,C);
return 0;
}
输出:
alpha : 90
beta : 45
gamma : 45
时间复杂度:由于使用内置 sqrt 函数,因此为 O(log(n))
辅助空间: O(1)
参考:
https://en.wikipedia.org/wiki/Law_of_cosines
如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。