Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

c++ 编写一个程序,点P到线段AB的最短距离

  1. User

    c++ 编写一个程序,点P到线段AB的最短距离

  2. Assistant

    以下是一个C++程序,用于计算点P到线段AB的最短距离:

    #include <iostream>
    #include <cmath>
    
    struct Point {
        double x;
        double y;
    };
    
    struct Segment {
        Point start;
        Point end;
    };
    
    // 计算两点之间的距离
    double distance(Point p1, Point p2) {
        return sqrt(pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2));
    }
    
    // 计算点P到线段AB的最短距离
    double shortestDistance(Point p, Segment seg) {
        double segLength = distance(seg.start, seg.end);
        
        // 线段长度为0,即线段是一个点
        if(segLength == 0) {
            return distance(p, seg.start);
        }
        
        // 计算线段的方向向量
        double directionX = (seg.end.x - seg.start.x) / segLength;
        double directionY = (seg.end.y - seg.start.y) / segLength;
        
        // 计算向量AP
        double apX = p.x - seg.start.x;
        double apY = p.y - seg.start.y;
        
        // 计算向量AP在线段方向向量上的投影长度
        double projection = apX * directionX + apY * directionY;
        
        // 将投影限制在线段范围内
        projection = std::max(0.0, std::min(projection, segLength));
        
        // 计算点P到线段投影点的距离
        double distanceToProjection = distance(p, Point { seg.start.x + projection * directionX,
                                                         seg.start.y + projection * directionY });
        
        return distanceToProjection;
    }
    
    int main() {
        Point p { 2.0, 3.0 };
        Segment seg { Point { 1.0, 2.0 }, Point { 4.0, 6.0 } };
        
        double shortestDist = shortestDistance(p, seg);
        
        std::cout << "Shortest distance from point P to segment AB: " << shortestDist << std::endl;
        
        return 0;
    }
    

    上述程序定义了两个结构体Point和Segment,分别表示一个点和一个线段。distance函数用于计算两点之间的距离。shortestDistance函数计算点P到线段AB的最短距离。程序中的main函数给出了一个示例,计算了点P(2, 3)到线段AB((1, 2), (4, 6))的最短距离,并输出结果。

    程序中的计算过程是根据几何学中的相关知识进行推导的。首先计算线段AB的长度,如果长度为0,即线段是一个点,那么点P到线段的距离就是点P到线段的起点的距离。如果线段不是一个点,那么首先计算线段的方向向量,然后计算向量AP在该方向向量上的投影长度。将投影长度限制在线段范围内,计算点P到线段投影点的距离即为最短距离。