Java 如何判断一条线是否触碰、相交或在圆外
圆是指在平面上以一定距离绕着给定点移动的封闭形状。线是没有厚度的直线一维图形,其在两个方向上无限延伸。
在本文中,我们将使用Java检查给定的线是否触碰圆或与圆相交。
我们将提供圆的中心坐标和半径,以及线的方程。我们需要检查给定的线是否与圆碰撞,从而出现三种可能的情况,如下所述:
- 如果线在圆外。
-
如果线触碰圆。
-
如果线与圆相交。
现在我们来检查上面的条件,比较圆心和线之间的垂直距离与圆的半径,将其命名为“d”。
现在,
- 如果d > r,则线在圆外。
-
如果d = r,则线接触圆。
-
如果d < r,则线与圆相交。
我们知道,线的方程为ax + by + c = 0
“d”可以用以下公式找到−
\mathrm{d=\frac{\rvert:ax_0:+:by_0:+:c:\lvert}{\sqrt{a^{2}:+:b^{2}}}}
开始吧!
展示一些实例
实例1
- 给定“d”的输入为−
- 半径=8,圆心=(0,0),a=2,b=5,c=3。
- 找到“d”的值后,结果为−
- 线在圆外。
实例2
- 给定“d”的输入为−
- 半径=2,圆心=(0,0),a=2,b=1,c=8。
- 找到“d”的值后,结果为−
- 线在圆外。
步骤
- 步骤1 −声明并初始化变量。
-
步骤2 −找到圆的中心1和中心2之间的距离。
-
步骤3 −检查距离的五种条件。
-
步骤4 −打印结果。
多种方法
我们以不同的方法提供了解决方案。
- 使用静态输入
-
使用用户定义的方法
让我们逐个查看程序及其输出。
方法1:使用静态输入
在这种方法中,将给定的半径、圆心、a、b和c的值赋给“d”。然后根据算法,我们将找出线是否接触、相交或在圆外。
实例
import java.io.*;
public class Main {
//main method
public static void main (String[] args){
//Declaring variables
int radius = 2;
int a = 2, b = 1, c = 8;
//Finding the distance of line from center of the circle
double dist = (Math.abs(a * 0 + b * 0 + c))/Math.sqrt(a * a + b * b);
// Check for different condition
if (radius == dist)
//print if line touches the circle
System.out.println ( "line touches the circle" );
else if (radius > dist)
//print if line intersects the circle
System.out.println( "line intersects the circle") ;
else
//print if line lie outside the circle
System.out.println( "line lie outside the circle") ;
}
}
输出
line lie outside the circle
方法2:使用用户定义的方法
在这种方法中,将半径、中心、a、b和c的值分配给找到“d”。然后按照算法,通过传递给定的值调用一个用户定义的方法,我们将找到线是否接触、相交或在圆外。
示例
import java.io.*;
public class Main {
//main method
public static void main (String[] args){
//Declaring variables
int radius = 8;
int a = 2, b = 5, c = 3;
//calling user defined method
func(a, b, c, radius);
}
//user defined method
static void func(int a, int b, int c, int radius){
//Finding the distance of line from center of the circle
double dist = (Math.abs(a * 0 + b * 0 + c))/Math.sqrt(a * a + b * b);
// Check for different condition
if (radius == dist)
//print if line touches the circle
System.out.println ( "line touches the circle" );
else if (radius > dist)
//print if line intersects the circle
System.out.println( "line intersects the circle") ;
else
//print if line lie outside the circle
System.out.println( "line lie outside the circle") ;
}
}
输出
line intersects the circle
在这篇文章中,我们使用Java编程语言探索了不同的方法来检查一条线是否与一个圆相接触、相交或位于圆外。