Solution - Calculate Distance between two points
Problem. Write a program that calculates the distance between two points in a 2D plane. The program should have a method called distance that takes in four double parameters representing the x and y coordinates of the two points and returns the distance between them.
Solution.
DistanceCalculator.java
public class DistanceCalculator {
public static void main(String[] args) {
double x1 = 1.0;
double y1 = 2.0;
double x2 = 4.0;
double y2 = 6.0;
double dist = distance(x1, y1, x2, y2);
// %.2f 表示占位符的位置 是一个 小数点后有两个数字 的小数
String msg = String.format("The distance between (%.2f, %.2f) and (%.2f, %.2f) is %.3f", x1, y1, x2, y2, dist);
System.out.printf(msg);
}
public static double distance(double x1, double y1, double x2, double y2) {
double d = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
return d;
}
}