温馨提示×

c语言怎么使用函数计算两点间距离

小亿
193
2024-02-29 09:29:15
栏目: 编程语言

要计算两点之间的距离,可以使用以下函数:

#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;
}

在这个程序中,我们首先定义了一个结构体Point表示一个点,包含了两个成员xy表示点的横纵坐标。然后定义了一个函数distance用于计算两个点之间的距离,函数内部使用了数学库中的sqrt函数来计算平方根。在main函数中定义了两个点point1point2,并调用distance函数计算它们之间的距离,最后输出结果。

0