4.以下程序用求两点间距离,补充完成程序。 public classPoint { int x, y;主代表点的x,y坐标 public Point ( int px.int y) { x=px ;__=y :} public double distance(Point a) { ___ Math.sqrt ( (x-a.x)*(x-a.x)+(y-a.y) *(y-a.y)) ;} public static void main(String args[]) { Point p1= new Point (4,12) : Point p2=new Point (26,51) : System.out. println(pi.__p2)) :}
时间: 2024-03-19 09:43:58 浏览: 15
下面是补充完成后的程序:
```
public class Point {
int x, y; // 表示点的 x,y 坐标
public Point(int px, int py) {
x = px;
y = py;
}
public double distance(Point a) {
return Math.sqrt((x - a.x) * (x - a.x) + (y - a.y) * (y - a.y));
}
public static void main(String args[]) {
Point p1 = new Point(4, 12);
Point p2 = new Point(26, 51);
System.out.println(p1.distance(p2));
}
}
```
这个程序定义了一个 `Point` 类,表示一个点,有两个属性 `x` 和 `y` 表示点的坐标。其中,`distance` 方法用于计算两个点之间的距离,输入参数是另一个点,输出结果是两个点之间的距离。在 `main` 方法中,我们创建了两个点 `p1` 和 `p2`,并且计算了它们之间的距离,然后输出结果。
相关问题
利用java程序给point类添加以下几个求两点间距的多态方法class Point{ int x;int y; public Point (int x,int y){ this.x=x;this.y=y;}}
可以添加以下几个求两点间距的多态方法:
1. 使用直线距离公式求解两点间距离:
```
public double distance(Point p) {
return Math.sqrt(Math.pow(this.x - p.x, 2) + Math.pow(this.y - p.y, 2));
}
```
这个方法接受一个 Point 参数,并返回当前点和传入点之间的距离。
2. 使用曼哈顿距离公式求解两点间距离:
```
public double distance(Point p) {
return Math.abs(this.x - p.x) + Math.abs(this.y - p.y);
}
```
这个方法同样接受一个 Point 参数,并返回当前点和传入点之间的曼哈顿距离。
3. 使用切比雪夫距离公式求解两点间距离:
```
public double distance(Point p) {
return Math.max(Math.abs(this.x - p.x), Math.abs(this.y - p.y));
}
```
这个方法同样接受一个 Point 参数,并返回当前点和传入点之间的切比雪夫距离。
注意,这三个方法使用了不同的距离公式,因此得到的距离可能不同。在实际应用中需要根据具体情况选择合适的距离公式。
给Point类添加以下几个求两点间距离的多态方法,并进行调用测试。 public double distance(Point p) 1求点与p点间距离 public double distance(int x,inty) /求点与(x,y) 点间距离 public static double distance(Point x,Pointy) /求x、y两点间距离
好的,关于你的问题,我们来逐一解答。
首先,给Point类添加以下多态方法:
```java
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public double distance(Point p) {
int dx = x - p.x;
int dy = y - p.y;
return Math.sqrt(dx * dx + dy * dy);
}
public double distance(int x, int y) {
return distance(new Point(x, y));
}
public static double distance(Point a, Point b) {
return a.distance(b);
}
}
```
这里我们添加了三个多态方法,分别是求点与p点间的距离、求点与(x,y)点间的距离和求两个点之间的距离。
其中,求点与p点间距离的方法直接调用了该点与另一个点之间的距离方法,而求点与(x,y)点间距离的方法则通过创建新的Point对象来调用第一个方法,最后求x、y两点间距离的方法则是调用了第一个方法。
接下来,我们进行测试:
```java
public static void main(String[] args) {
Point p1 = new Point(0, 0);
Point p2 = new Point(3, 4);
System.out.printf("distance between (%d, %d) and (%d, %d): %.2f%n",
p1.x, p1.y, p2.x, p2.y, p1.distance(p2));
System.out.printf("distance between (%d, %d) and (%d, %d): %.2f%n",
p1.x, p1.y, 3, 4, p1.distance(3, 4));
System.out.printf("distance between (%d, %d) and (%d, %d): %.2f%n",
p1.x, p1.y, p2.x, p2.y, Point.distance(p1, p2));
}
```
输出结果如下:
```
distance between (0, 0) and (3, 4): 5.00
distance between (0, 0) and (3, 4): 5.00
distance between (0, 0) and (3, 4): 5.00
```
我们可以看到,测试结果符合预期,三个多态方法均能正确计算两个点之间的距离。