欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 幼教 > C# 检查两个给定的圆是否相切或相交(Check if two given circles touch or intersect each other)

C# 检查两个给定的圆是否相切或相交(Check if two given circles touch or intersect each other)

2025/9/27 15:10:47 来源:https://blog.csdn.net/hefeng_aspnet/article/details/147071619  浏览:    关键词: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)

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词