1. 程式人生 > >[GIS演算法] 多邊形是否在圓內 - C語言實現

[GIS演算法] 多邊形是否在圓內 - C語言實現

/*
 @Time:20181112
 @Title:判斷多邊形是否在圓內
 @Desc:圓是一個凸集,判斷多邊形的每一個頂點是否在圓內即可
 */
#include<stdio.h>
#include<stdlib.h>

#define EXP 1e-8 //精度

typedef struct point{
	double x;
	double y;
	struct point *next;
}Point, *Polygon;
typedef struct circle{
	Point centre;
	double r;
}Circle;

int InitPolygon
(Polygon *p); //初始化多邊形 int InitCircle(Circle *c); //初始化圓 int PolygonInCircle(Polygon p, Circle C); //多邊形是否在圓內 int PointInCircle(Point A, Circle C); //點是否在圓內 /*測試資料 // 第一組 11 0 0 1 2 2 1 3 2 4 2 5 3 6 0 3 1 2 0 1 1.5 0 0 1 1 6 // 第二組 11 0 0 1 2 2 1 3 2 4 2 5 3 6 0 3 1 2 0 1 1.5 0 0 1 1 2 */ int main() { Polygon P; Circle C;
InitPolygon(&P); printf("Polygon init success\n"); InitCircle(&C); printf("circle init success\n"); printf("多邊形是否在圓內:%d", PolygonInCircle(P, C) ); return 0; } // 返回1:建立成功 // 返回0:建立不成功,點沒有閉合 int InitPolygon(Polygon *pHead) { int n; int i; Point *p,*q; double a,b; double suba, subb; scanf
("%d", &n); p = NULL; for (i=0; i<n; i++) { scanf("%lf%lf", &a, &b); q = (Point *)malloc(sizeof(Point)); if (!q) exit(0); q->x = a; q->y = b; // 連線 if (p==NULL) { //第一個點 q->next = q; //迴圈佇列 p = q; *pHead = q; } else { suba = (*pHead)->x - a; subb = (*pHead)->y - b; if ( suba>=-EXP && suba<=EXP && subb>=-EXP && subb<=EXP) {//閉合 構造完成 free(q); return 1; } p->next = q; q->next = *pHead; // 下一個 p = q; } } return 0; } // 返回1:建立成功 // 返回0:建立失敗 int InitCircle(Circle *c) { scanf("%lf%lf", &c->centre.x, &c->centre.y); scanf("%lf", &c->r); return 1; } // 多邊形是否在圓內 int PolygonInCircle(Polygon head, Circle c) { Point *p; p = head; do { if ( PointInCircle(*p, c)==0 ) return 0; p = p->next; } while (p!=head); return 1; } // 點是否在圓內 int PointInCircle(Point A, Circle C) { double d2; d2 = (A.x - C.centre.x) * (A.x - C.centre.x) + (A.y - C.centre.y) * (A.y - C.centre.y); if (d2 > C.r*C.r) { return 0; } else { return 1; } }