久久精品人人爽,华人av在线,亚洲性视频网站,欧美专区一二三

怎么用java求任意兩點之間的距離

184次閱讀
沒有評論

共計 1019 個字符,預計需要花費 3 分鐘才能閱讀完成。

要使用 Java 求任意兩點之間的距離,可以使用以下步驟:

  1. 創(chuàng)建一個名為 Point 的類,該類表示一個點。該類應該包含 xy兩個屬性,并提供相應的 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;
    }
}
  1. 創(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);
    }
}
  1. 在主程序中,創(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ì)的資源集合!

正文完
 
丸趣
版權(quán)聲明:本站原創(chuàng)文章,由 丸趣 2023-12-12發(fā)表,共計1019字。
轉(zhuǎn)載說明:除特殊說明外本站除技術(shù)相關以外文章皆由網(wǎng)絡搜集發(fā)布,轉(zhuǎn)載請注明出處。
評論(沒有評論)
主站蜘蛛池模板: 乌兰浩特市| 福贡县| 土默特右旗| 蒲江县| 鹤山市| 达孜县| 松溪县| 漯河市| 垦利县| 顺平县| 定远县| 沧源| 郧西县| 威信县| 阿拉善盟| 桃江县| 都兰县| 定州市| 上思县| 罗山县| 珲春市| 文登市| 陇川县| 平塘县| 新化县| 奉化市| 红安县| 阿鲁科尔沁旗| 安乡县| 蕲春县| 怀集县| 瓦房店市| 蒙城县| 玉树县| 仪征市| 师宗县| 神农架林区| 白山市| 沐川县| 乐都县| 昆山市|