c语言编写函数实现求两点间的距离。主函数输入两个点的坐标,调用函数求出两点的距离。
时间: 2024-05-12 17:19:41 浏览: 20
```
#include <stdio.h>
#include <math.h>
float distance(float x1, float y1, float x2, float y2) {
float dist = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
return dist;
}
int main() {
float x1, y1, x2, y2, dist;
printf("Enter the coordinates of point 1: ");
scanf("%f %f", &x1, &y1);
printf("Enter the coordinates of point 2: ");
scanf("%f %f", &x2, &y2);
dist = distance(x1, y1, x2, y2);
printf("The distance between the two points is: %f\n", dist);
return 0;
}
```
该程序中,`distance()`函数计算两点之间的距离,需要四个参数,分别为两个点的x和y坐标。主函数中通过`scanf()`函数获取两个点的坐标,然后调用`distance()`函数计算距离并输出结果。
相关问题
C语言编写一个函数计算两点间距离
可以使用以下代码实现:
```c
#include <stdio.h>
#include <math.h>
struct Point {
int x;
int y;
};
double distance(struct Point p1, struct Point p2) {
int dx = p1.x - p2.x;
int dy = p1.y - p2.y;
return sqrt(dx*dx + dy*dy);
}
int main() {
struct Point p1 = {0, 0};
struct Point p2 = {3, 4};
printf("Distance between (%d,%d) and (%d,%d) is %.2f\n",
p1.x, p1.y, p2.x, p2.y, distance(p1, p2));
return 0;
}
```
这里使用了一个结构体 `Point` 来表示点的坐标,`distance` 函数接受两个 `Point` 类型的参数,并计算它们之间的距离。在 `main` 函数中调用 `distance` 函数来计算两个点之间的距离,并输出结果。
c语言两点间距离代码
c语言计算两点间距离的代码可以如下:
```c
#include <stdio.h>
#include <math.h>
// 定义Point结构体表示一个点
typedef struct {
double x;
double y;
} Point;
// 计算两点间的距离
double calculateDistance(Point p1, Point p2) {
double distance;
distance = sqrt(pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2));
return distance;
}
int main() {
// 创建两个点对象
Point p1;
Point p2;
// 输入两个点的坐标
printf("请输入第一个点的x坐标:");
scanf("%lf", &p1.x);
printf("请输入第一个点的y坐标:");
scanf("%lf", &p1.y);
printf("请输入第二个点的x坐标:");
scanf("%lf", &p2.x);
printf("请输入第二个点的y坐标:");
scanf("%lf", &p2.y);
// 计算两点间的距离
double distance = calculateDistance(p1, p2);
printf("两点间的距离为:%.2lf\n", distance);
return 0;
}
```
以上代码通过定义一个Point结构体来表示一个点,然后定义了一个函数calculateDistance来计算两个点之间的距离。在主函数中,首先创建两个Point对象,然后通过输入的方式获取两个点的坐标,最后调用calculateDistance函数计算并输出两点之间的距离。