定义一个类,用于计算两点之间的距离
时间: 2024-05-13 11:19:42 浏览: 28
以下是一个计算两点之间距离的类的示例代码:
```python
import math
class Distance:
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def calculate(self):
distance = math.sqrt((self.x2 - self.x1) ** 2 + (self.y2 - self.y1) ** 2)
return distance
```
使用示例:
```python
# 创建一个Distance对象,传入两点坐标
d = Distance(1, 2, 4, 6)
# 调用calculate方法计算距离
result = d.calculate()
print(result) # 输出结果为 5.0
```
相关问题
描述 定义一个Point类(二维坐标中的点),采用成员函数distance来计算到原点的距离 输入 x,y轴坐标 输出 到原点距离,结果保留2位小数
以下是一个定义了Point类,采用成员函数distance计算到原点的距离的示例代码:
```python
#include <iostream>
#include <cmath>
using namespace std;
class Point {
public:
Point(double x, double y) {
this->x = x;
this->y = y;
}
double distance() {
return sqrt(x * x + y * y);
}
private:
double x, y;
};
int main() {
double x, y;
cin >> x >> y;
Point p(x, y);
printf("%.2f", p.distance());
return 0;
}
```
示例输出:
```python
2 2
2.83
```
首先我们定义了一个Point类,包含了构造函数和distance函数。在构造函数中,我们传入了两个参数x和y,表示二维坐标中的点的横纵坐标。在distance函数中,我们使用勾股定理计算了该点与原点之间的距离,并且返回了该距离值。
在main函数中,我们首先读入了用户输入的x和y坐标,然后使用这两个值来创建一个Point对象p。接着,我们调用p的distance函数来计算到原点的距离,并且将结果保留两位小数输出。
请定义一个Elephant 类,编写完整的类的声明和实现,请定义一个Elephant 类,编写完整的类的声明和实现,
class Elephant:
def __init__(self, name, age, height, weight):
self.name = name
self.age = age
self.height = height
self.weight = weight
def eat(self):
print(f"{self.name} is eating.")
def sleep(self):
print(f"{self.name} is sleeping.")
def play(self):
print(f"{self.name} is playing.")
def get_info(self):
return f"{self.name} is {self.age} years old, {self.height}cm tall and weighs {self.weight}kg."