Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

java - Finding if a circle is inside another circle

I'm having a bit of trouble. I have an assignment that requires me to find if a second circle is overlapping, inside, or neither a second circle. However, I am having trouble checking for overlapping and if the second circle is inside the first.

(variables used are x1, x2, y1, y2, r1, r2, distance)

Here's what I have:

if (distance > (r1 + r2)) {
        // No overlap
        System.out.println("Circle2 does not overlap Circle1");
    } else if (distance <= Math.abs(r1 + r2)) {
        // Overlap
        System.out.println("Circle2 overlaps Circle1");
    } else if ((distance <= Math.abs(r1 - r2)) {
        // Inside
        System.out.println("Circle2 is inside Circle1");
}

I fear the problem is with the overlapping and inside checks, but I cannot figure out how to properly set it up so I can reliably check if the second circle is inside the first.

Any help or advice would be greatly appreciated as I've tried multiple approaches but the solution simply escapes me every time.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you just need to check for inside before overlap as distance for inside is <= distance for overlap

if (distance > (r1 + r2)) 
{
    // No overlap
    System.out.println("Circle2 does not overlap Circle1");
}
else if ((distance <= Math.abs(r1 - r2)) 
{
    // Inside
    System.out.println("Circle2 is inside Circle1");
}
else              // if (distance <= r1 + r2)
{
   // Overlap
   System.out.println("Circle2 overlaps Circle1");
} 

answer modified as per Chris's comments


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...