Java 找出给定三角形的所有角度(Find all angles of a given triangle)

给定三角形在二维平面上所有三个顶点的坐标,任务是找到所有三个角度。
示例: 

输入: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) )

在三角学中,余弦定律(也称为余弦公式或余弦规则)将三角形边的长度与其某个角的余弦联系起来。

首先,计算所有边的长度。然后应用上述公式得到所有角度的弧度。然后将角度从弧度转换为度数。

以下是上述步骤的实施:

// Java Code to find all three angles 
// of a triangle given coordinate 
// of all three vertices 
  
import java.awt.Point; 
import static java.lang.Math.PI; 
import static java.lang.Math.sqrt; 
import static java.lang.Math.acos; 
  
class Test 

    // 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)sqrt(a2); 
    float b = (float)sqrt(b2); 
    float c = (float)sqrt(c2); 
      
    // From Cosine law 
    float alpha = (float) acos((b2 + c2 - a2)/(2*b*c)); 
    float betta = (float) acos((a2 + c2 - b2)/(2*a*c)); 
    float gamma = (float) acos((a2 + b2 - c2)/(2*a*b)); 
      
    // Converting to degree 
    alpha = (float) (alpha * 180 / PI); 
    betta = (float) (betta * 180 / PI); 
    gamma = (float) (gamma * 180 / PI); 
      
    // printing all the angles 
    System.out.println("alpha : " + alpha); 
    System.out.println("betta : " + betta); 
    System.out.println("gamma : " + gamma); 
    } 
      
    // Driver method 
    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); 
    } 
}  

 输出: 

alpha : 90
beta : 45
gamma : 45

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

辅助空间: O(1)

参考: 
https://en.wikipedia.org/wiki/Law_of_cosines

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

csdn_aspnet

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值