gpt4 book ai didi

Java - 两个圆重叠或在里面

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:14:50 34 4
gpt4 key购买 nike

我的家庭作业有问题,我无法完成最后一部分。我在这里做错了什么?它不会打印“Circle 2 overlaps Circle 1”。或“圆 2 不与圆 1 重叠”。前两种情况会打印出来。这是问题:

编写一个程序(TwoCircles.java),提示用户输入两个圆的圆心坐标和半径,并确定两者之间的几何关系,并据此打印以下消息之一:1. Circle 1 在 Circle 2 里面。2. 圆 2 在圆 1 里面。3. 圆圈 2 与圆圈 1 重叠。4. Circle 2 不与Circle 1 重叠。

这是我目前的代码:

import java.util.Scanner;
public class TwoCircles {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter Circle 1 center x-, y-coordinates, and radius: ");
double X1 = input.nextDouble();
double Y1 = input.nextDouble();
double radius1 = input.nextDouble();
System.out.print("Enter Circle 2 center x-, y-coordinates, and radius: ");
double X2 = input.nextDouble();
double Y2 = input.nextDouble();
double radius2 = input.nextDouble();

double distance = Math.pow((X1 - X2) * (X1 - X2) + (Y1 - Y2) * (Y1 - Y2), 0.5);

if (radius2 >= radius1){
if (distance <= (radius2 - radius1))
System.out.println("Circle 1 is inside Circle 2.");}
else if (radius1 >= radius2){
if (distance <= (radius1 - radius2))
System.out.println("Circle 2 is inside Circle 1.");}
else if (distance > (radius1 + radius2)){
System.out.println("Circle 2 does not overlap Circle 1.");}
else {
System.out.println("Circle 2 overlaps Circle 1.");}
}
}

感谢任何指导

最佳答案

使用以下代码:

import java.util.Scanner;
public class TwoCircles {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter Circle 1 center x-, y-coordinates, and radius: ");
double X1 = input.nextDouble();
double Y1 = input.nextDouble();
double radius1 = input.nextDouble();
System.out.print("Enter Circle 2 center x-, y-coordinates, and radius: ");
double X2 = input.nextDouble();
double Y2 = input.nextDouble();
double radius2 = input.nextDouble();
double distance = Math.pow((X1 - X2) * (X1 - X2) + (Y1 - Y2) * (Y1 - Y2), 0.5);
if (radius2 >= radius1 && distance <= (radius2 - radius1)){
System.out.println("Circle 1 is inside Circle 2.");
}
else if (radius1 >= radius2 && distance <= (radius1 - radius2) ) {
System.out.println("Circle 2 is inside Circle 1.");
}
else if (distance > (radius1 + radius2)){
System.out.println("Circle 2 does not overlap Circle 1.");
}
else {
System.out.println("Circle 2 overlaps Circle 1.");}
}
}

您使用的代码的问题在于前两个条件之一:

if(radius1>=radius2) 

else if(radius1<=radius2)

将始终为真,因此代码永远不会达到第三个或第四个条件。实现您正在尝试做的事情的正确方法是将我在上面提供的代码中完成的所有条件合并在一起。希望这对您有所帮助!

关于Java - 两个圆重叠或在里面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22032342/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com