共計 1019 個字符,預計需要花費 3 分鐘才能閱讀完成。
要使用 Java 求任意兩點之間的距離,可以使用以下步驟:
- 創(chuàng)建一個名為
Point
的類,該類表示一個點。該類應該包含x
和y
兩個屬性,并提供相應的 getter 和 setter 方法。
public class Point {private double x;
private double y;
public Point(double x, double y) {this.x = x;
this.y = 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;
}
}
- 創(chuàng)建一個名為
DistanceCalculator
的類,該類包含一個靜態(tài)方法calculateDistance
,用于計算兩點之間的距離。該方法接受兩個Point
對象作為參數(shù),并返回一個double
類型的距離值。
public class DistanceCalculator {public static double calculateDistance(Point point1, Point point2) {double xDiff = point2.getX() - point1.getX();
double yDiff = point2.getY() - point1.getY();
return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}
}
- 在主程序中,創(chuàng)建兩個
Point
對象,然后調(diào)用DistanceCalculator
的靜態(tài)方法來計算它們之間的距離。
public class Main {public static void main(String[] args) {Point point1 = new Point(1, 2);
Point point2 = new Point(3, 4);
double distance = DistanceCalculator.calculateDistance(point1, point2);
System.out.println("Distance between point1 and point2: " + distance);
}
}
上述代碼將輸出 "Distance between point1 and point2: 2.8284271247461903",表示兩點之間的距離為 2.8284271247461903。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完