为什么这个等式没有产生正确的回报?

时间:2015-06-30 18:10:20

标签: java

以下是我遇到问题的代码段。无论圆圈是否相交,程序返回它们都不相交。我在这里缺少什么?

if(intersectCir(xBlue, yBlue, radBlue, xRed, yRed, radRed) == true) {
         System.out.println("The blue circle intersects the red circle.");
     } else if(intersectCir(xBlue, yBlue, radBlue, xRed, yRed, radRed) != true){
         System.out.println("The blue circle does not intersect the red circle.");
     }

     if(intersectCir(xBlue, yBlue, radBlue, xGreen, yGreen, radGreen) == true) {
         System.out.println("The blue circle intersects the green circle.");
     } else if(intersectCir(xBlue, yBlue, radBlue, xGreen, yGreen, radGreen) != true){
         System.out.println("The blue circle does not intersect the green circle.");
     }

     if(intersectCir(xGreen, yGreen, radGreen, xRed, yRed, radRed) == true) {
         System.out.println("The green circle intersects the red circle.");
     } else if(intersectCir(xBlue, yBlue, radBlue, xRed, yRed, radRed) != true){
         System.out.println("The green circle does not intersect the red circle.");
     }
 }




 public static boolean intersectCir(int x1, int y1, int rad1, int x2, int y2, int rad2) {
     if(Math.sqrt(Math.pow(x1 - x2, 2)) + (Math.sqrt(Math.pow(y1 - y2, 2))) <= (rad1 + rad2));
         return true;
 }

}

2 个答案:

答案 0 :(得分:1)

这是你纠正的方法。

public static boolean intersectCir(int x1, int y1, int rad1, int x2, int y2, int rad2) {
 if(Math.sqrt(Math.pow(x1 - x2, 2)) + (Math.sqrt(Math.pow(y1 - y2, 2))) <= (rad1 + rad2))
     return true;
 else
     return false;

}

答案 1 :(得分:0)

您的距离公式被误译了。更正并评论如下:

  public static boolean intersectCir(int x1, int y1, int rad1, int x2, int y2, int rad2) {
    //distance formula, applied:
    //    ((x1-x2)^2+(y1-y2)^2)^0.5 <= rad1+rad2
    final int xdiff = x1 - x2;
    final int ydiff = y1 - y2;
    final int totalRad = rad1 + rad2;
    //    ((xdiff)^2+(ydiff)^2)^0.5 <= totalRad
    final int distanceSquared = xdiff * xdiff + ydiff * ydiff;//beware overflow!
    //    (distanceSquared)^0.5 <= totalRad
    //square roots are hard, better to just square both sides:
    //    distanceSquared <= totalRad^2
    return distanceSquared <= totalRad * totalRad;
  }