C# 检查两个给定的圆是否相切或相交(Check if two given circles touch or intersect each other)
有两个圆 A 和 B,圆心分别为C1(x1, y1)和C2(x2, y2),半径分别为R1和R2。任务是检查圆 A 和 B 是否相互接触。
例如:
输入: C1 = (3, 4)
C2 = (14, 18)
R1 = 5, R2 = 8
输出:圆圈互相不接触。
输入: C1 = (2, 3)
C2 = (15, 28)
R1 = 12, R2 = 10
输出:圆圈相互相交。
输入: C1 = (-10,8)
C2 = (14,-24)
R1 = 30,R2 = 10
方法:
中心 C1 和 C2 之间的距离计算如下
C1C2 = sqrt((x1 - x2) 2 + (y1 - y2) 2 )。
有三种情况会出现。
1、如果C1C2 <= R1 – R2:圆 B 位于 A 内。
2、如果C1C2 <= R2 – R1:圆 A 位于 B 内。
3、如果C1C2 < R1 + R2:圆互相相交。
4、如果C1C2 == R1 + R2:圆 A 和 B 相互接触。
5、否则,圆 A 和圆 B 不重叠
下面是上述方法的实现:
// C# program to check if two
// circles touch each other or not.
using System;
class GFG {
static void circle(int x1, int y1, int x2, int y2,
int r1, int r2)
{
double d = Math.Sqrt((x1 - x2) * (x1 - x2)
+ (y1 - y2) * (y1 - y2));
if (d <= r1 - r2) {
Console.Write("Circle B is inside A");
}
else if (d <= r2 - r1) {
Console.Write("Circle A is inside B");
}
else if (d < r1 + r2) {
Console.Write("Circle intersect"
+ " to each other");
}
else if (d == r1 + r2) {
Console.Write("Circle touch to"
+ " each other");
}
else {
Console.Write("Circle not touch"
+ " to each other");
}
}
// Driver code
public static void Main(String[] args)
{
int x1 = -10, y1 = 8;
int x2 = 14, y2 = -24;
int r1 = 30, r2 = 10;
circle(x1, y1, x2, y2, r1, r2);
}
}
// This article is contributed by Pushpesh Raj.
输出:
Circle touch to each other(圆互相触碰)
时间复杂度: O(log(n)),因为使用内置 sqrt 函数
辅助空间: O(1)
如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。