我正在尝试检查 Java 中的三角形是否为直角三角形。 这是测试类所做的一部分:
Triangle a = new Triangle(new Point(2, 2), new Point(6, 2), new Point(2, 6) );
System.out.println(a.isRight()); //Expects True
我的三角形类的一部分接收值并将它们设置为 x1、y2 等:
public Triangle(Point loc1, Point loc2, Point loc3) {
x1 = loc1.getX(); y1 = loc1.getY();
. . .
前两段代码是给我的。我要制作我制作的最后一段代码:
public boolean isRight() {
if((Math.pow(side1,2)+Math.pow(side2,2)) == Math.pow(side3,2))
return true;
if((Math.pow(side2,2)+Math.pow(side1,2)) == Math.pow(side3,2))
return true;
if((Math.pow(side3,2)+Math.pow(side2,2)) == Math.pow(side1,2))
return true;
else
return false;
}
但是,它仍然返回 false。我究竟做错了什么? 非常感谢!
更新: 谢谢您的帮助。我似乎犯了一个相当菜鸟式的错误。我从来没有想过 double 并不准确这一事实(抱歉,只是想简单地说一下我所做的事情)。我最终输入了这个:
if(Math.abs(side1*side1 + side2*side2 - side3*side3) < 0.2)
return true;
if(Math.abs(side1*side1 + side3*side3 - side2*side2) < 0.2)
return true;
if(Math.abs(side3*side3 + side2*side2 - side1*side1) < 0.2)
return true;
else
return false;
再次感谢您的帮助!
最佳答案
我看到了一些问题:
- 你检查 a2 + b2 = c2 和b2 + a2 = c< sup>2,但是这些其实是等价的
- 你永远不会检查 a2 + c2 = b sup>2.
- 您使用
Math.pow
来计算一个数的平方,这既低效又不精确。 (您应该只使用*
。) - 您希望浮点运算给出一个精确的值——适用于
==
——但它通常不会。
关于java - 检查三角形是否是直角三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27560034/