A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 杨建峰 中级黑马   /  2012-12-9 14:24  /  1134 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. /*
  2.     输入两个矩形的中心点和长与宽,判断两个矩形是相交还是在另一个之内或者不相交
  3.    
  4.     以下是代码,询问有没有更优方案,我总感觉自己打的,太繁琐了。
  5.    
  6.    
  7. */


  8. import java.util.Scanner;

  9. public class ZhengFang {
  10.             public static void main(String[] args) {
  11.                     Scanner input = new Scanner(System.in);

  12.         //输入第一个矩形的数据
  13.             System.out.print("Enter r1's center x-, y- coordinates, width, and height: ");
  14.                     double x1 = input.nextDouble();
  15.                     double y1 = input.nextDouble();
  16.                     double width1 = input.nextDouble();
  17.                     double height1 = input.nextDouble();

  18.         //输入第二个矩形的数据
  19.                     System.out.print("Enter r2's center x-, y- coordinates, width, and height: ");
  20.                     double x2 = input.nextDouble();
  21.                     double y2 = input.nextDouble();
  22.                     double width2 = input.nextDouble();
  23.                     double height2 = input.nextDouble();

  24.                     double x = Math.abs(x1 - x2);
  25.                     double y = Math.abs(y1 - y2);

  26.                     double width = width1 - width2;
  27.                     double height = height1 - height2;
  28.        
  29.                     double r1 = Math.hypot(width1 / 2, height1 / 2);
  30.                     double r2 = Math.hypot(width2 / 2, height2 / 2);
  31.                     double r = Math.hypot(x,y);

  32.         //通过公式判断两个矩形的情况
  33.         /*
  34.             1、两中心点的距离小于两矩形长宽各平方和的平方根的差,其中一个矩形的长和宽同时小于另一个的长和宽
  35.             则是包含
  36.             2、两中心点的距离大于两矩形长宽各平方和的平方根的差,并小于两矩形长宽各平方和的平方根的和,两矩形
  37.             的长或者宽的和大于两中心点的距离,则是交叉
  38.             3、以上都不是,则是不相叉
  39.         */
  40.                     if((r <= Math.abs(r1-r2)) && ((width1 > width2 && height1 > height2) || (width1 < width2 && height1 < height2))) {
  41.                                 System.out.println("inside");
  42.      }else if((r <= Math.abs(r1+r2)) && ((width1+width2)>x || (height1+height2)>y)) {
  43.                                 System.out.println("overlap");
  44.                     }else{
  45.                                 System.out.println("not overlap");
  46.                     }

  47.         }
  48. }
复制代码

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马