point类求两点间的距离,点到原点的距离

本文介绍了一个简单的Java程序,该程序定义了一个名为point的类,用于表示二维平面上的点,并提供了计算两点间距离的方法。通过静态导入,简化了数学函数的调用。展示了如何实例化对象并调用成员方法来计算点到点的距离及点到原点的距离。
package zzy;
import static java.lang.Math.pow;
import static java.lang.Math.sqrt;
import static java.lang.System.*;

public class point {
    public static void main(String[] args){
        point dian = new point(24,7);
        out.println(dian.distence(18,12));
        dian.distence();
    }
    private int x;
    private int y;
    public point(int x,int y){
        this.x = x;
        this.y = y;
    }
    public void show(){
        out.println("("+x+","+y+")");
    }
    public double distence(double x ,double y){
        double a_ = sqrt(pow(this.x-x,2)+pow(this.y-y,2)); 
        return(a_);
    }
    public void distence()
    {
        out.println(sqrt(pow(this.x,2)+pow(this.y,2)));
    }
}

# 题目重述 采用面向对象的思想设计一个程序,用于计算二维平面上两点距离。要的坐标封装在中,并提供计算两点距离的方法。 --- # 给出答案(答案为带注释的代码块) ```java // Point :表示二维平面上的一个 class Point { private double x; // 横坐标 private double y; // 纵坐标 // 构造函数:初始化的坐标 public Point(double x, double y) { this.x = x; this.y = y; } // 获取横坐标 public double getX() { return x; } // 设置横坐标 public void setX(double x) { this.x = x; } // 获取纵坐标 public double getY() { return y; } // 设置纵坐标 public void setY(double y) { this.y = y; } // 计算当前到另一个距离 // 公式:$d = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}$ public double distance(Point other) { if (other == null) { throw new IllegalArgumentException("另一个不能为null"); } double dx = this.x - other.x; double dy = this.y - other.y; return Math.sqrt(dx * dx + dy * dy); } // 计算原点 (0,0) 的距离 public double distanceFromOrigin() { return Math.sqrt(x * x + y * y); } // 重写 toString 方法,便于输出信息 @Override public String toString() { return String.format("Point(%.2f, %.2f)", x, y); } } // 主:测试两点距离计算功能 public class DistanceCalculator { public static void main(String[] args) { // 创建两个:P1(1.0, 2.0) 和 P2(4.0, 6.0) Point p1 = new Point(1.0, 2.0); Point p2 = new Point(4.0, 6.0); // 输出两个 System.out.println(" P1: " + p1); System.out.println(" P2: " + p2); // 计算输出两点距离 double dist = p1.distance(p2); System.out.printf("两点距离为:%.2f\n", dist); // 计算 P1 到原点距离 System.out.printf("P1 到原点距离为:%.2f\n", p1.distanceFromOrigin()); } } ``` --- # 代码解析 1. **`Point` **: - 封装了二维的两个属性 `x` 和 `y`; - 提供构造方法初始化坐标; - 提供 getter/setter 方法; - `distance(Point other)` 方法实现核心算法:使用欧几里得距离公式; - 支持与 `null` 的安全判断和异常处理。 2. **距离计算公式**: $$ d = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2} $$ 使用 `Math.sqrt()` 和平方运算实现。 3. **主测试逻辑**: - 创建两个 `Point` 对象; - 调用 `distance()` 方法获取结果; - 格式化输出结果,增强可读性。 --- # 知识(列出该代码中遇到的知识) 1. **的封装与属性定义** 将的坐标私有化,通过方法访问,保证数据安全性。 2. **欧几里得距离公式应用** 使用数学库 `Math.sqrt()` 实现两点直线距离计算。 3. **对象作为方法参数传递** `distance(Point other)` 接收另一个对象实例进行计算
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值