给定三角形在二维平面上所有三个顶点的坐标,任务是找到所有三个角度。
示例:
输入: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) )
在三角学中,余弦定律(也称为余弦公式或余弦规则)将三角形边的长度与其某个角的余弦联系起来。
首先,计算所有边的长度。然后应用上述公式得到所有角度的弧度。然后将角度从弧度转换为度数。
以下是上述步骤的实施:
// C# Code to find all three angles
// of a triangle given coordinate
// of all three vertices
using System;
class GFG
{
class Point
{
public int x, y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
}
// returns square of distance b/w two points
static int lengthSquare(Point p1, Point p2)
{
int xDiff = p1.x - p2.x;
int yDiff = p1.y - p2.y;
return xDiff * xDiff + yDiff * yDiff;
}
static void printAngle(Point A, Point B, Point 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 = (float)Math.Sqrt(a2);
float b = (float)Math.Sqrt(b2);
float c = (float)Math.Sqrt(c2);
// From Cosine law
float alpha = (float) Math.Acos((b2 + c2 - a2) /
(2 * b * c));
float betta = (float) Math.Acos((a2 + c2 - b2) /
(2 * a * c));
float gamma = (float) Math.Acos((a2 + b2 - c2) /
(2 * a * b));
// Converting to degree
alpha = (float) (alpha * 180 / Math.PI);
betta = (float) (betta * 180 / Math.PI);
gamma = (float) (gamma * 180 / Math.PI);
// printing all the angles
Console.WriteLine("alpha : " + alpha);
Console.WriteLine("betta : " + betta);
Console.WriteLine("gamma : " + gamma);
}
// Driver Code
public static void Main(String[] args)
{
Point A = new Point(0, 0);
Point B = new Point(0, 1);
Point C = new Point(1, 0);
printAngle(A, B, C);
}
}
// This code is contributed by Rajput-Ji
输出:
alpha : 90
beta : 45
gamma : 45
时间复杂度:由于使用内置 sqrt 函数,因此为 O(log(n))
辅助空间: O(1)
参考:
https://en.wikipedia.org/wiki/Law_of_cosines
如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。