Javascript 使用余弦定理寻找三角形第三边的程序(Program to find third side of triangle using law of cosines)

 给定两条边 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))

示例代码:

// Javascript program to find third
// side of triangle using
// law of cosines
 
    // Function to calculate
    // cos value of angle c
    function cal_cos( n) {
        let accuracy = 0.0001, x1;
        let 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 =  Math.cos(n);
        let i = 1;
        do {
            denominator = 2 * i * (2 * i - 1);
            x1 = -x1 * n * n / denominator;
            cosx = cosx + x1;
            i = i + 1;
        } while (accuracy <= Math.abs(cosval - cosx));
 
        return cosx;
    }
 
    // Function to find third side
    function third_side( a, b, c) {
        let angle = cal_cos(c);
 
        return  Math.sqrt((a * a) + (b * b) - 2 * a * b * angle);
    }
 
    // Driver code
      
        let c = 49;
        let a = 5, b = 8;
 
        // function call
        document.write(Math.round(third_side(a, b, c) * 100000.0) / 100000.0);
 
// This code is contributed by Rajput-Ji  

输出:

6.04339

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

辅助空间:O(1),因为我们不使用任何额外空间。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

csdn_aspnet

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

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

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

打赏作者

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

抵扣说明:

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

余额充值