package 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 */ //此处添加代码 }
时间: 2023-06-20 14:09:26 浏览: 96
以下是 Line 类的代码,包括添加的求两条线的交点和求点到线的距离的方法:
```java
package 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;
}
/**
* 求两条线的交点
*
* @param other 另一条线
* @return 交点,若不存在则返回 null
*/
public Point getIntersection(Line other) {
double x1 = p1.x, y1 = p1.y, x2 = p2.x, y2 = p2.y;
double x3 = other.p1.x, y3 = other.p1.y, x4 = other.p2.x, y4 = other.p2.y;
double d = (y2 - y1) * (x4 - x3) - (x2 - x1) * (y4 - y3);
if (Math.abs(d) < 1e-6) { // 平行或重合
return null;
}
double ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / d;
double ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / d;
if (ua < 0 || ua > 1 || ub < 0 || ub > 1) { // 不相交
return null;
}
double x = x1 + ua * (x2 - x1);
double y = y1 + ua * (y2 - y1);
return new Point(x, y);
}
/**
* 求点到线的距离
*
* @param point 点
* @return 点到线的距离
*/
public double distanceToPoint(Point point) {
double x1 = p1.x, y1 = p1.y, x2 = p2.x, y2 = p2.y;
double x0 = point.x, y0 = point.y;
double numerator = Math.abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1);
double denominator = Math.sqrt(Math.pow(y2 - y1, 2) + Math.pow(x2 - x1, 2));
return numerator / denominator;
}
}
```
其中,求两条线的交点的方法使用了向量叉积的知识进行计算。如果两条直线平行或者共线,那么它们没有交点,此时返回 null。否则,计算出交点的坐标并返回。
求点到线的距离的方法使用了点到直线距离公式进行计算。公式中的分子表示点到直线的距离的绝对值,分母表示直线的长度,两者相除即可得到点到直线的距离。
阅读全文