黑马程序员技术交流社区
标题:
两矩形相叉问题
[打印本页]
作者:
杨建峰
时间:
2012-12-9 14:24
标题:
两矩形相叉问题
/*
输入两个矩形的中心点和长与宽,判断两个矩形是相交还是在另一个之内或者不相交
以下是代码,询问有没有更优方案,我总感觉自己打的,太繁琐了。
*/
import java.util.Scanner;
public class ZhengFang {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//输入第一个矩形的数据
System.out.print("Enter r1's center x-, y- coordinates, width, and height: ");
double x1 = input.nextDouble();
double y1 = input.nextDouble();
double width1 = input.nextDouble();
double height1 = input.nextDouble();
//输入第二个矩形的数据
System.out.print("Enter r2's center x-, y- coordinates, width, and height: ");
double x2 = input.nextDouble();
double y2 = input.nextDouble();
double width2 = input.nextDouble();
double height2 = input.nextDouble();
double x = Math.abs(x1 - x2);
double y = Math.abs(y1 - y2);
double width = width1 - width2;
double height = height1 - height2;
double r1 = Math.hypot(width1 / 2, height1 / 2);
double r2 = Math.hypot(width2 / 2, height2 / 2);
double r = Math.hypot(x,y);
//通过公式判断两个矩形的情况
/*
1、两中心点的距离小于两矩形长宽各平方和的平方根的差,其中一个矩形的长和宽同时小于另一个的长和宽
则是包含
2、两中心点的距离大于两矩形长宽各平方和的平方根的差,并小于两矩形长宽各平方和的平方根的和,两矩形
的长或者宽的和大于两中心点的距离,则是交叉
3、以上都不是,则是不相叉
*/
if((r <= Math.abs(r1-r2)) && ((width1 > width2 && height1 > height2) || (width1 < width2 && height1 < height2))) {
System.out.println("inside");
}else if((r <= Math.abs(r1+r2)) && ((width1+width2)>x || (height1+height2)>y)) {
System.out.println("overlap");
}else{
System.out.println("not overlap");
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2