ckage JavaPlane; class Line { private Point p1; private Point p2; public Line(Point p1,Point p2) { this.p1 = p1; this.p2 = p2; } public double getLength() { return Math.sqrt(Math.pow(p1.x-p2.x, 2)+Math.pow(p1.y-p2.y, 2)); } Point getStartPoint() { return p1; } Point getEndPoint() { return p2; } public static boolean point_on_line(Point point, Line line) { Point p1 = Point.sub(line.getStartPoint(), point); Point p2 = Point.sub(line.getEndPoint(), point); return Math.abs(Point.crossProduct(p1, p2)) < 1e-6; } /** * 求两条线的交点 * @return point */ //此处添加代码 /** * 求点到线的距离 * @return double */ //此处添加代码 } package JavaPlane; public class Test { public static void main(String[] args) { Point p1 = new Point(0,0); Point p2 = new Point(1,1); Point p3 = new Point(1,0); Point p4 = new Point(0,0.9); if(p1.compare(p2)) //测试两个点重合 System.out.println("两个点是同一个点"); else System.out.println("两个点不是同一个点"); if(p3.colinear(p1,p2)) //测试三点共线 System.out.println("三点共线"); else System.out.println("三点不共线"); Line l1 = new Line(p1,p2); System.out.println("线的长度:"+l1.getLength()); if(l1.point_on_line(p3, l1)) //测试点在线上 System.out.println("点在线上"); else System.out.println("点不在线上"); double r1 = 1; double r2 = 1; Circle c1 = new Circle(p1,r1); System.out.println("圆c1的面积:"+c1.getArea()); System.out.println("圆c1的圆心坐标:"+c1.getCenter().x+","+c1.getCenter().y); if(c1.point_in_circle(p4, c1)) System.out.println("点在圆内"); else System.out.println("点不在圆内"); Circle c2 = new Circle(p2, r2); Point[] points = Circle.intersect(c1, c2); //测试求两个圆的交点 if (points != null){ System.out.println("第1个交点的坐标:"+points[0].x+","+points[0].y); System.out.println("第2个交点的坐标:"+points[1].x+","+points[1].y); } // 测试求两个线的交点 // 此处添加代码 // 测试求点到线的距离 // 此处添加代码 } }
时间: 2023-06-19 18:07:01 浏览: 97
在 Line 类中添加求两条线的交点和求点到线的距离的方法:
```
public Point getIntersection(Line line) {
double x1 = this.p1.x, y1 = this.p1.y;
double x2 = this.p2.x, y2 = this.p2.y;
double x3 = line.p1.x, y3 = line.p1.y;
double x4 = line.p2.x, y4 = line.p2.y;
double d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
if (d == 0) {
return null;
}
double xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d;
double yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d;
return new Point(xi, yi);
}
public double getDistance(Point point) {
double x0 = point.x;
double y0 = point.y;
double x1 = this.p1.x;
double y1 = this.p1.y;
double x2 = this.p2.x;
double y2 = this.p2.y;
double a = y2 - y1;
double b = x1 - x2;
double c = x2 * y1 - x1 * y2;
double d = Math.abs(a * x0 + b * y0 + c) / Math.sqrt(a * a + b * b);
return d;
}
```
在 Test 类中测试求两个线的交点和求点到线的距离的方法:
```
Point p5 = new Point(0.5, 0.5);
Line l2 = new Line(p3, p4);
System.out.println("点到线的距离:" + l1.getDistance(p5));
Point intersection = l1.getIntersection(l2);
if (intersection != null) {
System.out.println("两条线的交点:" + intersection.x + "," + intersection.y);
} else {
System.out.println("两条线没有交点");
}
```
阅读全文