【发布时间】:2013-09-13 20:44:40
【问题描述】:
我正在尝试编写一个程序来确定一个圆是否在一个矩形内/是否接触到一个矩形。用户输入圆的中心点和半径,以及矩形的两个对角点。
我不确定如何包含圆的圆周上的所有点,以说明至少有一个点在/接触矩形。有人知道怎么做吗?
当我运行我当前的程序时,我会故意输入一个矩形内的圆点,并且应该使用我输入的 if 语句,但它会打印出错误的答案。
import java.util.Scanner;
public class lab4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double cx, cy, x, y, r, p1x, p1y, p2x, p2y, max;//input
String a;
System.out.print("Enter cx: ");
cx = in.nextDouble();
System.out.print("Enter cy: ");
cy = in.nextDouble();
System.out.print("Enter r: ");
r = in.nextDouble();
System.out.println("Enter x value of point 1:");
p1x = in.nextDouble();
System.out.println("Enter y value of point 1:");
p1y = in.nextDouble();
System.out.println("Enter x value of point 2:");
p2x = in.nextDouble();
System.out.println("Enter y value of point 2:");
p2y = in.nextDouble();
max = p2x;
if (p1x > max)
max = p1x;
max = p2y;
if (p1y > max)
max = p1y;
if (cx >= p1x && cx <= p2x)
a = "Circle is inside of Rectangle";
if (cx >= p1x && cx <= p2x)
a = "Circle is inside of Rectangle";
if (cx+r >= p1x && cx+r <= p2x)
a = "Circle is inside of Rectangle";
if (cx-r >= p1x && cx-r <= p2x)
a = "Circle is inside of Rectangle";
if (cy >= p1y && cy <= p2y)
a = "Circle is inside of Rectangle";
if (cy >= p1y && cy <= p2y)
a = "Circle is inside of Rectangle";
if (cy+r >= p1y && cy+r <= p2y)
a = "Circle is inside of Rectangle";
if (cy-r >= p1y && cy-r <= p2y)
a = "Circle is inside of Rectangle";
else
a = "Circle is outside of Rectangle";
System.out.println(a);
【问题讨论】:
-
您的 else 仅适用于最后一个 if,而不适用于所有,也许您覆盖了一个值,相反,我建议 将每个结果连接到变量 a 并查看所有结果
标签: java if-statement geometry rectangles