给定两条边 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))
示例代码:
# Python3 program to find third side
# of triangle using law of cosines
import math as mt
# Function to calculate cos
# value of angle c
def cal_cos(n):
accuracy = 0.0001
x1, denominator, cosx, cosval = 0, 0, 0, 0
# 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 = mt.cos(n)
i = 1
while (accuracy <= abs(cosval - cosx)):
denominator = 2 * i * (2 * i - 1)
x1 = -x1 * n * n / denominator
cosx = cosx + x1
i = i + 1
return cosx
# Function to find third side
def third_side(a, b, c):
angle = cal_cos(c)
return mt.sqrt((a * a) +
(b * b) - 2 * a * b * angle)
# Driver Code
c = 49
a, b = 5, 8
print(third_side(a, b, c))
# This code is contributed by mohit kumar
输出:
6.04339
时间复杂度:O(log(n)),因为使用内置 sqrt 函数
辅助空间:O(1),因为我们不使用任何额外空间。
如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。