Java Point 类实现距离计算:距离公式及代码示例
以下是Java编写的Point类,包含distance方法:
public class Point {
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double distance(double x2, double y2) {
double dx = x2 - x;
double dy = y2 - y;
return Math.sqrt(dx*dx + dy*dy);
}
}
使用方法:
Point p = new Point(0, 0);
double d = p.distance(3, 4);
System.out.println(d); // 输出5.0
该代码演示了如何创建一个Point对象,并使用distance方法计算它与另一个点的距离。通过这个例子,您可以学习如何使用Java Point类进行距离计算,并应用于各种实际应用场景。
原文地址: https://www.cveoy.top/t/topic/ohlk 著作权归作者所有。请勿转载和采集!