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:通过计算三角形面积
在这个方法中,程序中将初始化三个点。然后通过使用公式计算三角形的面积。如果面积为零,则打印三个点共线。
示例
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中检查三个点是否共线。