设置点类point求两点之间距离
时间: 2023-05-19 17:02:30 浏览: 50
可以使用以下代码来求两点之间的距离:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance(p1, p2):
return ((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2) ** 0.5
p1 = Point(1, 2)
p2 = Point(3, 4)
print(distance(p1, p2)) # 输出:2.8284271247461903
相关问题
设置点类point求两点之间距离,利用成员函数
可以使用以下代码实现:
```cpp
#include <iostream>
#include <cmath>
class Point {
public:
Point(double x, double y) : x_(x), y_(y) {}
double distanceTo(const Point& other) const {
double dx = x_ - other.x_;
double dy = y_ - other.y_;
return std::sqrt(dx * dx + dy * dy);
}
private:
double x_;
double y_;
};
int main() {
Point p1(0, 0);
Point p2(3, 4);
std::cout << "Distance between p1 and p2 is " << p1.distanceTo(p2) << std::endl;
return 0;
}
```
这个程序定义了一个点类 Point,其中包含了两个成员变量 x 和 y,表示点的坐标。类中还定义了一个成员函数 distanceTo,用于计算当前点与另一个点之间的距离。在主函数中,我们创建了两个点 p1 和 p2,并调用 p1 的 distanceTo 函数来计算两点之间的距离。
定义类point求两点距离
好的,这是一个简单的类point的定义,可以用来计算两点之间的距离:
```python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
dx = self.x - other.x
dy = self.y - other.y
return (dx ** 2 + dy ** 2) ** 0.5
```
使用方法:
```python
p1 = Point(0, 0)
p2 = Point(3, 4)
print(p1.distance(p2)) # 输出 5.0
```
希望这个回答能够帮到你!