设计一个MyPoint类,表示具有x坐标和y坐标的点
时间: 2024-06-06 21:10:39 浏览: 132
class MyPoint:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "Point(" + str(self.x) + ", " + str(self.y) + ")"
def distance(self, other_point):
return ((self.x - other_point.x) ** 2 + (self.y - other_point.y) ** 2) ** 0.5
def move(self, dx, dy):
self.x += dx
self.y += dy
相关问题
设计名为MyPoint的类表示一个平面坐标点--具有x坐标和y坐标的点,该类包括, 成员变量:x、y;double型; 无参数的构造方法:MyPoint( ),创建坐标点0,0); 带参数的构造方法:MyPoint(double x,double y) 创建一个坐标点(x,y); 成员方法:getX()、getY(),返回坐标点相应的值; 成员方法:distance( ),返回MyPoint类型的两个点之间的距离; 编写测试类程序创建两个点 (2,3) 和 (10,30.5)的对象,并显示它们之间的距离。
以下是MyPoint类的实现:
```
public class MyPoint {
private double x;
private double y;
public MyPoint() {
this.x = 0;
this.y = 0;
}
public MyPoint(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double distance(MyPoint other) {
double dx = this.x - other.x;
double dy = this.y - other.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
```
以下是测试程序的实现:
```
public class MyPointTest {
public static void main(String[] args) {
MyPoint p1 = new MyPoint(2, 3);
MyPoint p2 = new MyPoint(10, 30.5);
double distance = p1.distance(p2);
System.out.println("The distance between (" + p1.getX() + ", " + p1.getY() + ") and (" + p2.getX() + ", " + p2.getY() + ") is " + distance);
}
}
```
输出结果为:
```
The distance between (2.0, 3.0) and (10.0, 30.5) is 28.460498941515414
```
MyPoint类表示二维坐标中的一个点,具有两个double类型属性: 横坐标 纵坐标
请问如何在Java中实现MyPoint类?
可以使用以下代码实现MyPoint类:
public class MyPoint {
private double x;
private double y;
public MyPoint(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public void setX(double x) {
this.x = x;
}
public void setY(double y) {
this.y = y;
}
public double distance(MyPoint p) {
double dx = x - p.getX();
double dy = y - p.getY();
return Math.sqrt(dx * dx + dy * dy);
}
}
阅读全文