以下是C语言射线法求解{2, 1}在多边形{ {{0, 0}, {2, 0}}, {{2, 0}, {1, 1}},{{1, 1}, {2, 2}}, {{2, 2}, {0, 2}}, {{0, 2}, {0, 0}} }内的代码:

#include <stdio.h>

typedef struct {
    double x;
    double y;
} Point;

typedef struct {
    Point start;
    Point end;
} Segment;

int isPointInPolygon(Point point, Segment *segments, int count) {
    int i, j;
    int intersections = 0;
    Segment ray = { point, { point.x + 1.0, point.y } }; // 构造射线

    for (i = 0; i < count; i++) {
        Segment segment = segments[i];
        if (segment.start.y == segment.end.y) { // 水平线段跳过
            continue;
        }
        if (ray.start.y < segment.start.y && ray.end.y < segment.start.y) { // 射线在线段下方
            continue;
        }
        if (ray.start.y > segment.start.y && ray.end.y > segment.start.y) { // 射线在线段上方
            continue;
        }
        double x = segment.start.x + (segment.end.x - segment.start.x) * (ray.start.y - segment.start.y) / (segment.end.y - segment.start.y); // 计算交点横坐标
        if (x > point.x) { // 交点在射线右侧
            intersections++;
        }
    }

    return intersections % 2 == 1; // 奇数次交点在多边形内,偶数次交点在多边形外
}

int main() {
    Point point = { 2, 1 };
    Segment segments[] = { { { 0, 0 }, { 2, 0 } }, { { 2, 0 }, { 1, 1 } }, { { 1, 1 }, { 2, 2 } }, { { 2, 2 }, { 0, 2 } }, { { 0, 2 }, { 0, 0 } } };
    int count = sizeof(segments) / sizeof(segments[0]);

    if (isPointInPolygon(point, segments, count)) {
        printf("{2, 1}在多边形内\n");
    } else {
        printf("{2, 1}在多边形外\n");
    }

    return 0;
}

输出结果为:

{2, 1}在多边形内
``
2 1在多边形 0 0 2 0 2 0 1 11 1 2 2 2 2 0 2 0 2 0 0 内吗?C语言射线法求解

原文地址: https://www.cveoy.top/t/topic/fkRC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录