2018-05-01
判断点和圆的关系
判断一个点和圆的关系
1)圆外
2)圆上
3)圆内
转换成代码:一般名词要么是对象,要么是状态;而动词是方法
思路:比较半径和两点之间的距离
代码实现:
1 //把点对象抽象成类 2 class Points 3 { 4 private int x;//横坐标 5 private int y;//纵坐标 6 7 Points(int x, int y){ 8 this.x = x; 9 this.y = y; 10 } 11 12 //get方法 13 public int getX(){ 14 return x; 15 } 16 public int getY(){ 17 return y; 18 } 19 //set方法 20 public void setX(int x){ 21 this.x = x; 22 } 23 public void setY(int y){ 24 this.y = y; 25 } 26 27 } 28 //把圆抽象成对象 29 class Circle 30 { 31 private int r;//半径 32 33 Circle(int r){ 34 this.r = r; 35 } 36 37 /* 38 判断点和圆的关系 39 参数: 需要判断的点的对象 40 返回: 41 1:圆外 42 0:圆上 43 -1:圆内 44 45 */ 46 public int jude(Points p){ // public int 表示要返回int类型的值 47 //x的平方和加上y的平方和 48 int xxyy = p.getX() * p.getX() + p.getY() * p.getY(); 49 int rr = this.r * this.r; 50 51 if(rr > xxyy){ 52 System.out.println("点在圆内"); 53 return -1;//返回值的同时结束方法 54 }else if(rr < xxyy){ 55 System.out.println("点在圆外"); 56 return 1; 57 }else{ 58 System.out.println("点在圆上"); 59 return 0; 60 61 } 62 63 } 64 } 65 66 67 68 69 //判断点和圆的关系 70 class PointDemo 71 { 72 public static void main(String[] args) 73 { 74 //创建一个点对象(3,4) 75 Points p = new Points(3,4); 76 77 //创建一个半径为5的对象 78 Circle c = new Circle(5); 79 80 //调用方法 81 int ret = c.jude(p); 82 //打印结果 83 System.out.println(ret); 84 } 85 }
输出结果: