我试图检查三角形在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。我究竟做错了什么?谢谢一群!
更新:感谢您的帮助。我似乎犯了一个相当愚蠢的错误。我从没想过双打并不十分准确(抱歉,只是想简单地说出我的所作所为)。我最终输入了这个:
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;
再次感谢您的帮助!
我看到了许多问题:
Math.pow
通常使用平方来计算效率和精确度。(您应该只使用*
。)==
-通常不会提供。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句