定义一个Point,求两点之间最短距离,c++
时间: 2023-06-12 08:03:46 浏览: 59
Point 是一个表示二维平面上一个点的类。它通常包含两个成员变量 x 和 y,分别表示该点在横轴和纵轴上的坐标。我们可以定义 Point 类如下:
```python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
```
现在我们想要求两个 Point 对象之间的最短距离。我们可以使用勾股定理来计算两点之间的距离。假设我们有两个 Point 对象 p1 和 p2,它们的坐标分别为 (x1, y1) 和 (x2, y2),两点之间的距离 c 可以根据以下公式计算:
c = sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
其中,sqrt() 函数表示求平方根。我们可以在 Point 类中添加一个方法来计算两点之间的距离:
```python
from math import sqrt
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
return sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2)
```
现在我们可以创建两个 Point 对象,并计算它们之间的距离:
```python
p1 = Point(0, 0)
p2 = Point(3, 4)
c = p1.distance(p2)
print(c) # 输出 5.0
```
这里的 c 就是两点之间的最短距离。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)