用java编写point类,有两个属性xy,一个方法,distance(point p1,point p2.)计算两者的距离

如题所述

Java程序:

class Point {
protected double x;
protected double y;

public Point() {
x = 0;
y = 0;
}

public Point(double x, double y) {
this.x = x;
this.y = y;
}

public static double distance(Point p1, Point p2) {
return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
}
}
public class Main {
public static void main(String[] args) {
Point p1 = new Point(0, 0);
Point p2 = new Point(1, 2);

System.out.println("p1、p2两点之间的距离:" + Point.distance(p1, p2));
}
}


运行测试:

p1、p2两点之间的距离:2.23606797749979
温馨提示:内容为网友见解,仅供参考
第1个回答  2017-06-24
参考:
public class Strecke {
Punkt p1, p2;
Strecke (Punkt punkt1, Punkt punkt2) {
this.p1 = punkt1;
this.p2 = punkt2;
}
public Punkt mittelPunkt() {
return new Punkt ((p1.getX()+p2.getX())/2, (p1.getY()+p2.getY())/2);
}
public double abstand() {
return Math.sqrt(
(p1.getX() - p2.getX()) * (p1.getX() - p2.getX()) +
(p1.getY() - p2.getY()) * (p1.getY() - p2.getY())
);
}
static public void main (String args[]) {
Strecke s = new Strecke (new Punkt(2.0, 2.0), new Punkt(5.0, 6.0));
Punkt mp = s.mittelPunkt();
System.out.println ("Midpoint = (" + mp.getX() + "," + mp.getY() + ")");
double as = s.abstand();
System.out.println ("Length = " + as);
}
}本回答被网友采纳
相似回答