用c++写一个两点之间的距离 并且两个点由我输入得到
时间: 2023-05-23 09:00:55 浏览: 63
好的,以下是用 C 语言编写计算两点间距离的代码:
```
#include <stdio.h>
#include <math.h>
int main()
{
float x1, y1, x2, y2, distance;
printf("请输入第一个点的坐标(x1,y1):\n");
scanf("%f%f", &x1, &y1);
printf("请输入第二个点的坐标(x2,y2):\n");
scanf("%f%f", &x2, &y2);
distance = sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2));
printf("两点之间的距离为:%f\n", distance);
return 0;
}
```
该程序首先提示用户输入两个点的坐标,然后利用勾股定理计算两点间距离,并输出结果。
说明:该问题属于编程类问题,可以回答。
相关问题
定义一个Point,求两点之间最短距离,c++
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 就是两点之间的最短距离。
用C++写一个输出三维两条平行线段之间的垂直距离
以下是一个用C++实现的计算三维两条平行线段之间垂直距离的函数:
```c++
#include <iostream>
#include <cmath>
using namespace std;
struct Point {
double x, y, z;
};
double distance(Point p1, Point p2) {
return sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2) + pow(p1.z - p2.z, 2));
}
double verticalDistance(Point p1, Point p2, Point p3, Point p4) {
double d1 = distance(p1, p2);
double d2 = distance(p3, p4);
double d3 = distance(p1, p3);
double h = sqrt(pow(d1, 2) - pow((d3 * d3 - pow(d2, 2) - pow(d1, 2)) / (-2 * d2), 2));
return h;
}
int main() {
Point p1 = {1, 2, 3};
Point p2 = {4, 5, 6};
Point p3 = {1, 2, 5};
Point p4 = {4, 5, 8};
double h = verticalDistance(p1, p2, p3, p4);
cout << "垂直距离为:" << h << endl;
return 0;
}
```
在这个程序中,我们定义了一个 `Point` 结构体来表示三维空间中的一个点。`distance` 函数用于计算两个点之间的距离。`verticalDistance` 函数接收四个点作为参数,分别表示两条平行线段的两个端点,然后计算出两条线段之间的垂直距离。最后,我们在 `main` 函数中调用 `verticalDistance` 函数,并输出计算结果。