How to use functions in C language to calculate the distance between two points?
To calculate the distance between two points, you can use the following function:
#include <stdio.h>
#include <math.h>
// 定义结构体表示点
typedef struct {
double x;
double y;
} Point;
// 计算两点之间的距离
double distance(Point p1, Point p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return sqrt(dx*dx + dy*dy);
}
int main() {
// 定义两个点
Point point1 = {1.0, 2.0};
Point point2 = {3.0, 4.0};
// 计算两点之间的距离
double dist = distance(point1, point2);
// 输出结果
printf("The distance between the two points is: %.2f\n", dist);
return 0;
}
In this program, we first define a struct Point representing a point, which includes two members x and y representing the point’s horizontal and vertical coordinates. Then we define a function distance to calculate the distance between two points, using the sqrt function from the math library to calculate the square root. In the main function, we define two points, point1 and point2, and call the distance function to calculate the distance between them, finally outputting the result.