用C++求两个点间的距离
时间: 2024-03-22 09:42:53 浏览: 20
可以使用勾股定理求解,代码如下:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double x1, y1, x2, y2;
cout << "Enter the coordinates of point 1: ";
cin >> x1 >> y1;
cout << "Enter the coordinates of point 2: ";
cin >> x2 >> y2;
double distance = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
cout << "The distance between the two points is: " << distance << endl;
return 0;
}
```
在上面的代码中,我们使用 `sqrt()` 函数来计算平方根,使用 `pow()` 函数来计算底数的次方。用户需要输入两个点的坐标,代码将计算并输出这两个点之间的距离。
相关问题
两点间距离用C++语言写
可以使用以下代码来计算两点间的距离:
```c
#include <stdio.h>
#include <math.h>
int main() {
double x1, y1, x2, y2, distance;
printf("请输入第一个点的坐标(x1, y1): ");
scanf("%lf%lf", &x1, &y1);
printf("请输入第二个点的坐标(x2, y2): ");
scanf("%lf%lf", &x2, &y2);
distance = sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2));
printf("两点之间的距离为: %lf\n", distance);
return 0;
}
```
这段代码会让用户分别输入两点的坐标,然后使用勾股定理来计算两点之间的距离,并将结果显示出来。这样,用户就可以使用 C 语言来计算任意两点之间的距离了。
c++如何实现两点间距离计算
计算两点之间的距离可以使用勾股定理,即:
d = √((x2-x1)² + (y2-y1)²)
其中,(x1, y1) 和 (x2, y2) 分别是两个点的坐标,d 是两点之间的距离。
C 语言实现如下:
```c
#include <stdio.h>
#include <math.h>
int main() {
double x1, y1, x2, y2, distance;
printf("请输入第一个点的坐标 (x1, y1):");
scanf("%lf %lf", &x1, &y1);
printf("请输入第二个点的坐标 (x2, y2):");
scanf("%lf %lf", &x2, &y2);
distance = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
printf("两点之间的距离为:%.2lf\n", distance);
return 0;
}
```
运行程序后,依次输入两个点的坐标即可计算它们之间的距离。注意,需要使用 math.h 头文件中的 sqrt 和 pow 函数来进行平方根和平方运算。