计算机java编程_计算机java编程

展开全部

这个要求中 distance 返回应该是double类型,而不是int类型, 因为 两点之间的距离不636f70793231313335323631343130323136353331333363393034可能是整数,double强制转换为int可能会超过Integer的最大值,代码如下:public class Point {

private Integer x;

private Integer y;

/**

* @param x

* @param y

*/

public Point(Integer x, Integer y) {

super();

this.x = x;

this.y = y;

}

/**

* @return the x

*/

public Integer getX() {

return x;

}

/**

* @param x the x to set

*/

public void setX(Integer x) {

this.x = x;

}

/**

* @return the y

*/

public Integer getY() {

return y;

}

/**

* @param y the y to set

*/

public void setY(Integer y) {

this.y = y;

}

public double distance(Point p) {

if(null == p) {

p = new Point(0,0);//if p is null, default point x=0 and y=0

}

double result = 0;

result = Math.abs(Math.sqrt(Math.pow(this.getX().intValue() -p.getX().intValue(),2)+Math.pow(this.getY().intValue() -p.getY().intValue(),2)));

return result;

}

public static void  main(String[] args) {

Point point1 = new Point(1,1);

Point point2 = new Point(0,-1);

double distance = point1.distance(point2);

System.out.println(distance);

}

}

打印结果:

2.23606797749979

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值