计算两点坐标距离与中点坐标 |
您所在的位置:网站首页 › java两点之间距离公式 › 计算两点坐标距离与中点坐标 |
/*回顾一下数学公式: 两点的坐标是(x1, y1)和(x2, y2) 则两点之间的距离公式为 d=√[(x1-x2)²+(y1-y2)²] 注意特例: 当x1=x2时 两点间距离为|y1-y2| 当y1=y2时 两点间距离为|x1-x2| 中点坐标:midpoint(X,Y) X=(X1+X2)/2 Y=(Y1+Y2)/2 */ //自定义坐标类 public class Pointer { private double x; private double y; public Pointer(double x,double y){//构造方法初始化 this.setX(x); this.setY(y); } public double getX() { return x; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } //两点之间的距离 public static double distance(Pointer a,Pointer b){//静态方法,通过类名.方法名调用 double result= (Math.pow(a.getX()-b.getX(),2)+Math.pow(a.getY()-b.getY(),2)); return Math.sqrt(result); } public void display(){ System.out.println("("+this.getX()+","+this.getY()+")"); } public String toString(){ return "("+x+","+y+")"; } public boolean equals(Pointer obj){ if(this.getX()==obj.getX()&&this.getY()==obj.getY()){ return true; } return false; } //两点坐标的中点 public static String minpoint(Pointer a,Pointer b){ double x=(a.getX()+b.getX())/2; double y=(a.getY()+b.getY())/2; return "("+x+","+y+")"; } }
//测试类 public class Demotest { public static void main(String[] args) { Pointer [] test=new Pointer [2];//对象数组 test[0]=new Pointer(2, 2); test[1]=new Pointer(3,3); test[0].display(); test[1].display(); System.out.println("**********************开始**********************"); System.out.println(test[0].toString()+test[1].toString()+"两点之间的距离:"+Pointer.distance(test[0], test[1])); System.out.println(test[0].toString()+test[1].toString()+"两点的中点坐标是:"+Pointer.minpoint(test[0], test[1])); System.out.println(test[0].equals(test[1])); } } /*******************当然也可选择JDK里面的Pointer类****************/ import java.awt.Point;import java.util.Scanner; public class Test { public static void main(String[] args){ System.out.println("请输入有几组:"); Scanner scanner = new Scanner(System.in); int groupCount = scanner.nextInt(); double results[] = new double[groupCount]; for (int i=0;i |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |