java怎么计算两点间的距离

56次阅读
没有评论

共计 618 个字符,预计需要花费 2 分钟才能阅读完成。

在 Java 中,可以使用以下公式来计算两点之间的距离:

import java.lang.Math;

public class DistanceCalculator {public static double calculateDistance(double x1, double y1, double x2, double y2) {double distance;
        distance = Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2));
        return distance;
    }

    public static void main(String[] args) {double x1 = 1, y1 = 2;
        double x2 = 3, y2 = 4;
        double distance = calculateDistance(x1, y1, x2, y2);
        System.out.println("The distance between the two points is: " + distance);
    }
}

在上述示例中,我们定义了一个名为 DistanceCalculator 的类,其中包含了一个静态方法 calculateDistance,该方法接受四个参数:两个点的 x 和 y 坐标。方法内部使用了欧几里得距离公式来计算两点之间的距离。在main 方法中,我们定义了两个点的坐标,并调用 calculateDistance 方法计算它们之间的距离。最后,我们将结果打印到控制台。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-09发表,共计618字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)