所以我试图编写一个简单的方法,它接受四个坐标集并确定它们是否形成正方形。我的方法是从一个点开始,计算其他三个点与基点之间的距离。由此我们可以得到具有相同值的两条边和一条对角线。然后我使用毕达哥拉斯定理来查找边的平方是否等于对角线。如果是 isSquare 方法返回 true 否则 false。我想要的东西找出是否有一些我可能会错过的情况,或者方法是否有问题。感谢您的所有帮助。
public class CoordinatesSquare {
public static boolean isSquare(List<Point> listPoints) {
if (listPoints != null && listPoints.size() == 4) {
int distance1 = distance(listPoints.get(0), listPoints.get(1));
int distance2 = distance(listPoints.get(0), listPoints.get(2));
int distance3 = distance(listPoints.get(0), listPoints.get(3));
if (distance1 == distance2) {
// checking if the sides are equal to the diagonal
if (distance3 == distance1 + distance2) {
return true;
}
} else if (distance1 == distance3) {
// checking if the sides are equal to the diagonal
if (distance2 == distance1 + distance3) {
return true;
}
}
}
return false;
}
private static int distance(Point point, Point point2) {
//(x2-x1)^2+(y2-y1)^2
return (int) (Math.pow(point2.x - point.x, 2) + (Math.pow(point2.y
- point.y, 2)));
}
public static void main(String args[]) {
List<Point> pointz = new ArrayList<Point>();
pointz.add(new Point(2, 2));
pointz.add(new Point(2, 4));
pointz.add(new Point(4, 2));
pointz.add(new Point(4, 4));
System.out.println(CoordinatesSquare.isSquare(pointz));
}
}
//Point Class
public class Point {
Integer x;
Integer y;
boolean isVisited;
public Point(Integer x, Integer y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
if(obj!=null && obj.getClass().equals(this.getClass())){
return ((Point) obj).x.equals(this.x)&&((Point) obj).y.equals(this.y);
}
return false;
}
}
您知道,您可以更轻松地进行相同的检查。您只需检查两件事:
“四点构成一个平行四边形”和“其中一个角是直角”。
第一个为真,当P3 = P1 + (P2-P1) + (P4-P1)
第二个当(P2-P1)*(P4-P1) = 0
Where A*B
是点积(A.x * B.x + A.y * B.y)
这里唯一的问题是计算错误。你不能期望浮点数完全相等,所以而不是A=B
你应该考虑使用类似的东西abs(A-B) < E
where E
对于您的情况来说足够小。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)