C++ distance 如何测量两点间距离

c++
1472
2024/8/12 13:21:27
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C++中,可以使用以下方法来测量两点之间的距离:

#include <iostream>
#include <cmath>

struct Point {
    double x;
    double y;
};

double distance(Point p1, Point p2) {
    return sqrt(pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2));
}

int main() {
    Point point1 = {1.0, 2.0};
    Point point2 = {4.0, 6.0};
    
    double dist = distance(point1, point2);
    
    std::cout << "Distance between point1 and point2 is: " << dist << std::endl;
    
    return 0;
}

在上面的示例中,定义了一个Point结构体表示一个点的坐标,然后定义了一个distance函数来计算两个点之间的距离。在main函数中,创建了两个点point1point2,并计算它们之间的距离并输出。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: C++ Halcon中如何进行颜色空间转换