java中distance怎么用

Java 中 distance 方法通过欧几里德公式计算两点之间的欧几里德距离:1. 用法:double distance(Point2D p);2. 返回值:两点间的欧几里德距离。

Java 中的 distance 方法

distance 方法是 Java 中 java.awt.geom 包下 Point2D 类及其子类(如 Point)的方法。它用于计算两个点之间的距离。

用法:

double distance(Point2D p)

其中,p 是要计算距离的另一个点。

返回值:

distance 方法返回这两个点之间的欧几里德距离。

例子:

Point p1 = new Point(0, 0);
Point p2 = new Point(3, 4);

double distance = p1.distance(p2);
System.out.println("两点之间的距离为:" + distance);

输出:

两点之间的距离为:5.0

详细解释:

distance 方法使用欧几里德公式计算两点之间的距离:

distance = sqrt((x2 - x1)^2 + (y2 - y1)^2)

其中,(x1, y1) 是一个点的坐标,(x2, y2) 是另一个点的坐标。

注意:

  • 对于 Point 类,distance 方法与 Point2D 类相同。
  • 如果 pnull,则抛出 NullPointerException
  • 返回的距离是一个浮点数。