c++ 判断点和折线 距离

目录

点在折线y方向的投影的距离

判断点是否在折线下方,不求距离


点在折线y方向的投影的距离

x相同时,y的差异。

#include <iostream>
#include <vector>
#include <cmath>
#include <limits>

struct Point {
    double x, y;
};

double calculateYDifferenceToPolyline(const std::vector<Point>& polyline, const Point& a) {
    double minDifference = std::numeric_limits<double>::infinity();

    for (size_t i = 0; i < polyline.size() - 1; ++i) {
        const Point& P1 = polyline[i];
        const Point& P2 = polyline[i + 1];

        // 检查点 a 是否在 P1 和 P2 之间的 x 范围内
        if ((a.x >= P1.x && a.x <= P2.x) || (a.x >= P2.x && a.x <= P1.x)) {
            // 计算 a 在 P1 -> P2 线段上的对应 y 坐标
            double yLine = P1.y + (P2.y - P1.y) * (a.x - P1.x) / (P2.x - P1.x);

            // 计算 y 方向上的差异
            double difference = a.y - yLine;

            // 更新最小差异
            minDifference = std::min(minDifference, std::abs(difference));
        }
    }

    return minDifference;
}

int main() {
    // 定义折线
    std::vector<Point> polyline = {
        {1.0, 1.0}, {2.0, 3.0}, {3.0, 3.0}, {4.0, 5.0}, {5.0, 5.0}, {6.0, 7.0}
    };

    // 定义需要判断的点
    Point a = { 3.5, 3.5 };

    // 计算 a 与折线段的 y 方向差异
    double difference = calculateYDifferenceToPolyline(polyline, a);

    std::cout << "dis: " << difference << " units." << std::endl;

    return 0;
}

判断点是否在折线下方,不求距离

#include <iostream>
#include <vector>

struct Point {
    double x, y;
};

int checkPointRelativeToPolyline(const std::vector<Point>& polyline, const Point& P3) {
    int isBelow = 0;

    for (size_t i = 0; i < polyline.size() - 1; ++i) {
        const Point& P1 = polyline[i];
        const Point& P2 = polyline[i + 1];

        // 计算向量叉积
        double crossProduct = (P2.x - P1.x) * (P3.y - P1.y) - (P2.y - P1.y) * (P3.x - P1.x);


        if (crossProduct < 0) {
            isBelow = 1;
        }

    }

    return isBelow;

}

int main() {
    // 定义折线
    std::vector<Point> polyline = {
        {1.0, 1.0}, {2.0, 3.0}, {3.0, 3.0}, {4.0, 5.0}, {5.0, 5.0}, {6.0, 7.0}
    };

    // 定义需要判断的点
    Point P3 = { 3.5, 4.0 };

    // 检查 P3 相对于折线的每个线段的位置
    checkPointRelativeToPolyline(polyline, P3);

    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI算法加油站

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值