Java 如何检查给定的两个圆是否相交或接触
圆是由点在平面上移动而形成的封闭形状,使其与给定点的距离保持不变。在本文中,我们将检查两个给定的圆是否相交或相接。
我们将给出两个圆的中心1(即x1、y1)和中心2(即x2、y2),以及半径R1和R2。我们需要检查给定的圆是否与另一个圆碰撞,因此可能会出现以下五种情况-
- 圆2位于圆1内部
-
圆1位于圆2内部
-
圆1和圆2相交
-
圆1和圆2相接
-
圆1和圆2不重叠
现在,要检查上述条件,我们将找到中心1和中心2之间的距离,并将其命名为“d”。
现在,
- 1. 如果d≤R1-R2:圆2位于圆1内部
-
2. 如果d≤R2-R1:圆1位于圆2内部
-
3. 如果d
-
4. 如果
d==R1+R2
:圆1和圆2相接 -
5. 否则,圆1和圆2不重叠
可以使用以下公式找到“d”:
d=\sqrt{(x1-x2)^2+(y1-y2)^2}
让我们开始吧!
展示一些实例
示例1
- 给定的“d”的输入是-
- 中心1=(9,3),中心2=(11,1),R1=5,R2=4。
- 找到“d”的值后,结果将是-
- 圆1和圆2相交
示例2
- 给定的 d 的输入为 –
- Center 1 = (5, 8), Center 2 = (9, 11), R1 = 20 , R2 = 40 .
- 找到了 “d” 的值后,结果将是 –
- Circle 1 在 Circle 2 内部
步骤
- 步骤1 - 声明和初始化变量。
-
步骤2 - 找到圆的中心 1 和中心 2 之间的距离。
-
步骤3 - 检查距离的五个条件。
-
步骤4 - 打印结果。
多种方法
我们提供了不同的解决方法。
- 通过使用静态输入
-
通过使用用户定义的方法
让我们逐个查看程序及其输出。
方法1:通过使用静态输入
在这种方法中,半径 1 和半径 2,圆心 1 和圆心 2 的值将被赋值给找到的 “d”。然后根据算法,我们将找到线是否接触、相交或位于圆外。
示例
public class Main {
//main method
public static void main(String[] args){
//declaring variables
int x1 = 9, y1 = 3;
int x2 = 11, y2 = 1;
int r1 = 5, r2 = 4;
//finding d using the formula
double d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
if (d <= r1 - r2) {
//print if Circle 2 lie inside circle 1
System.out.println("Circle 2 lie inside circle 1");
}
else if (d <= r2 - r1) {
//print if Circle 1 lie inside 2
System.out.println("Circle 1 lie inside 2");
}
else if (d < r1 + r2) {
//print if Circle 1 and 2 intersect each other
System.out.println("Circle 1 and 2 intersect each other");
}
else if (d == r1 + r2) {
//print if Circle 1 and 2 touch each other
System.out.println("Circle 1 and 2 touch each other");
} else {
//print if Circle 1 and 2 do not touch each other
System.out.println("Circle 1 and 2 do not touch each other");
}
}
}
输出
Circle 1 and 2 intersect each other
方法2:通过使用用户定义的方法
在这种方法中,半径1和半径2、中心点1和中心点2的值将被分配给找到“d”。然后通过传递给定的值调用一个用户定义的方法,根据算法我们将找到该线是否触碰、相交或在圆外。
示例
public class Main {
//main method
public static void main(String[] args){
//declaring variables
int x1 = 5, y1 = 8;
int x2 = 9, y2 = 11;
int r1 = 20, r2 = 40;
//calling user defined method
func(x1, y1, x2, y2, r1, r2);
}
//user defined method
static void func(int x1, int y1, int x2, int y2, int r1, int r2){
//finding d using the formula
double d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
if (d <= r1 - r2) {
//print if Circle 2 lie inside circle 1
System.out.println("Circle 2 lie inside circle 1");
}
else if (d <= r2 - r1) {
//print if Circle 1 lie inside 2
System.out.println("Circle 1 lie inside 2");
}
else if (d < r1 + r2) {
//print if Circle 1 and 2 intersect each other
System.out.println("Circle 1 and 2 intersect each other");
}
else if (d == r1 + r2) {
//print if Circle 1 and 2 touch each other
System.out.println("Circle 1 and 2 touch each other");
}
else {
//print if Circle 1 and 2 do not touch each other
System.out.println("Circle 1 and 2 do not touch each other");
}
}
}
输出
Circle 1 lie inside 2
在这篇文章中,我们使用Java编程语言探索了不同的方法来判断两个给定的圆是否相交或相切。