c++ 找出给定三角形的所有角度(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) )

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

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

以下是上述步骤的实施:

// 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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

csdn_aspnet

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

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

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

打赏作者

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

抵扣说明:

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

余额充值