我正在尝试用 Java 创建一个程序,当用户输入边长时计算任何三角形的内角。我见过一些与此类似的问题,但我无法让我的问题工作。
我希望它以度为单位计算角度,但它总是给我错误的答案或不是数字(NaN)。我尝试将所有内容放入一个方程式中,以防它只是舍入误差,但它只是给出了相同的答案。我已将其恢复为这种格式,以使其更易于阅读。
public class Triangles
{
// variables already declared and user inputs double sideOne, sideTwo, sideThree
threeSq=sideThree*sideThree;
twoSq=sideTwo*sideTwo;
oneSq=sideOne*sideOne;
public static double getAngleOne(double oneSq, double twoSq, double threeSq, double sideOne, double sideTwo, double sideThree)
{
double angOne;
angOne = (oneSq + twoSq - threeSq) / (2 * sideOne * sideTwo);
angOne = Math.toRadians(angOne);
angOne = Math.acos(angOne);
angOne = Math.toDegrees(angOne);
return angOne;
}
public static double getAngleTwo(double oneSq, double twoSq, double threeSq, double sideOne, double sideTwo, double sideThree)
{
double angTwo;
angTwo = (twoSq + threeSq - oneSq) / (2 * sideTwo * sideThree);
angTwo = Math.toRadians(angTwo);
angTwo = Math.acos(angTwo);
angTwo = Math.toDegrees(angTwo);
return angTwo;
}
public static double getAngleThree(double oneSq, double twoSq, double threeSq, double sideOne, double sideTwo, double sideThree)
{
double angThree;
angThree = (oneSq + threeSq - twoSq) / (2 * sideOne * sideThree);
angThree = Math.toRadians(angThree);
angThree = Math.acos(angThree);
angThree = Math.toDegrees(angThree);
return angThree;
}
}
我正在使用余弦定律,但它没有给我正确的答案。例如,当我输入边长为 3、3 和 3 时,它会给出 71.68993312052173;当我输入 5、6 和 7(分别为 1、2 和 3 边)时,我得到 NaN。
编辑: 感谢您的建议,我已将所有整数更改为 double ,我的数学就是问题(忘记了 oneSq + TwoSq - ThreeSq 周围的括号)
我提出了完整修改后的代码,但它仍然给出了错误的答案,对于所有边都相同的三角形,它应该为所有三个返回 60,但它返回 89.49999365358626。
最佳答案
修正比率的计算后,仍然剩下一件事要做:丢失线条
angOne = Math.toRadians(angOne);
此时,angOne 不包含任何角度。如果边遵守三角形不等式,则 angOne 此时应包含 -1 到 1 之间的数字,无需转换。
<小时/>等边三角形的面积比为0.5。转换为弧度、acos、转换为度数的操作可以组合为
M*acos(x/M) = M*(pi/2-asin(x/M)),
乘数 M=180/pi。由于 x/M 很小,因此结果大约为
M*(pi/2-x/M)=90-x,
结果接近 89.5,如您上次试验中获得的那样。
<小时/>当然,想要的结果是M*acos(0.5)=M*(pi/3)=60。
关于java - 内角的余弦定律,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23446065/