编写余弦定律计算

Writing a law of cosines calculation

我正在尝试使用余弦定律在 C 中创建一个函数,returns 三角形与给定角度相反的边的长度。

现在我得到了适用于 excel 的公式,它给出了正确的结果。然而,当我在 C 中尝试时,我得到了错误的结果,我无法弄清楚为什么。

对于测试,我将 sideA 设为 21.1,sideB 设为 19,它们之间的角度设为 40 度。现在答案应该是 14.9,就像我在 excel 中得到的一样。但是在 C 中我得到 23.735。请有人帮我找出我哪里出错了

// Find the length of a side of a triangle that is oppisit a given angle using the Law Of Cosine
// for example using an triangle that is 21.1cm on one side, 19 cm on the other and an angle of 40 degreese inbetween then....
// in excel it worked and the formuler was  =SQRT(POWER(23.1;2)+POWER(19;2)-2*(23.1)*(19)*COS(40*(3.14159/180))) = 14.9 cm
float my_Trig_LawOfCos_OppSideLength(float centerAngle, float sideA, float sideB)
    {
        float sideLengthPow2= (pow(sideA,2) + pow(sideB,2))) - ((2*sideA*sideB)*cos(centerAngle*(3.14159/180));
        float sideLength = sqrt(sideLengthPow2);
        return sideLength;
    }

如果您以错误的顺序传递参数,就会发生这种情况。你把边长23.1放在角的位置

def oppside(ang, lA, lB): return (lA**2+lB**2-2*(lA)*(lB)*cos(ang*(pi/180)))**0.5

oppside(40,19,23.1)
>>> 14.905575729577208

oppside(19,23.1,40)
>>> 19.65430416708927

oppside(23.1,19,40)
>>> 23.72490935854042

通常,您可以通过生成一个显示错误结果的最小可执行示例来发现此类错误,因为这样您还可以记录错误的函数调用(甚至可能亲眼看到)。