如何在Java中檢查三個點是否共線?


如果三個點都位於一條直線上,則稱這三個點共線。如果這些點不在同一條直線上,則它們不是共線點。

這意味著如果三個點 (x1, y1), (x2, y2), (x3, y3) 在同一條直線上,則它們共線。

其中,x1、y1、x2、y2、x3、y3 是 x 軸和 y 軸上的點,(x1, y1)、(x2, y2)、(x3, y3) 是座標。

在數學上,有兩種方法可以知道三個點是否共線。

透過使用這些點找到三角形的面積,如果三角形的面積為零,則三個點共線。

Formula to find area of triangle = 0.5 * [x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)]

透過找到兩點的斜率是否相等,如果相等,則所有三個點都共線。

Formula to find slope =
Slope of (x1, y1), (x2, y2)
m1 = (y2-y1) / (x2-x1)
Slope of (x2, y2), (x3, y3)
m2 = (y3-y2) / (x3-x2)

在本文中,我們將瞭解如何使用 Java 程式語言檢查三個點是否共線。

向您展示一些例項

例項 1

假設給定的座標是 (1,2), (3,4), (5,6)

所有三個點都共線,因為它們位於同一條直線上。

例項 2

假設給定的座標是 (1,1), (1,4), (1,6)

所有三個點都共線,因為它們位於同一條直線上。

例項 3

假設給定的座標是 (1,1), (2,4), (4,6)

所有三個點都不共線,因為它們不在同一條直線上。

演算法

  • 步驟 1 - 透過使用者輸入或初始化獲取三個點。

  • 步驟 2 - 使用上述任何一個公式,檢查三角形面積是否為零或斜率是否相同,然後列印三個點共線,否則列印三個點不共線。

  • 步驟 3 - 列印結果。

多種方法

我們提供了不同方法的解決方案。

  • 透過查詢三角形面積。

  • 透過查詢斜率。

讓我們逐一檢視程式及其輸出

方法 1:透過查詢三角形面積

在這種方法中,三個點將在程式中初始化。然後使用公式計算三角形的面積。如果面積為零,則列印三個點共線。

示例

public class Main{ //main method public static void main(String args[]){ //initialized first point double x1 = 1; double y1 = 2; System.out.println("First point: "+x1+", "+y1); //initialized second point double x2 = 3; double y2 = 4; System.out.println("Second point: "+x2+", "+y2); //initialized third point double x3 = 5; double y3 = 6; System.out.println("Third point: "+x3+", "+y3); //find triangle area by using formula double triangleArea = 0.5*(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)); System.out.println("Area of triangle using three points ="+triangleArea); if (triangleArea == 0) System.out.println("Three points are collinear."); else System.out.println("Three points are not collinear."); } }

輸出

First point: 1.0, 2.0
Second pointe: 3.0, 4.0
Third pointe: 5.0, 6.0
Area of triangle using three points = 0.0
Three points are collinear.
.

方法 2:透過查詢斜率

在這種方法中,三個點將在程式中初始化。然後計算任意一對點的斜率,並使用斜率公式檢查該斜率是否等於另一對點的斜率。如果兩個斜率相等,則列印三個點共線。

示例

public class Main{ //main method public static void main(String args[]){ //initialized first point double x1 = 1; double y1 = 2; System.out.println("First point: "+x1+", "+y1); //initialized second point double x2 = 3; double y2 = 4; System.out.println("Second point: "+x2+", "+y2); //initialized third point double x3 = 5; double y3 = 6; System.out.println("Third point: "+x3+", "+y3); //find slope of (x1, y1) , (x2, y2) double m1 = (y2-y1) / (x2-x1); //find slope of (x2, y2) , (x3, y3) double m2 = (y3-y2) / (x3-x2); System.out.println("Slope of first pair= " + m1); System.out.println("Slope of second pair= " + m2); if (m1 == m2) System.out.println("Three points are collinear."); else System.out.println("Three points are not collinear."); } }

輸出

First point: 1.0, 2.0
Second point: 3.0, 4.0
Third point: 5.0, 6.0
Slope of first pair= 1.0
Slope of second pair= 1.0
Three points are collinear.

在本文中,我們探討了如何使用不同的方法在 Java 中檢查三個點是否共線。

更新於:2022 年 10 月 27 日

2K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.