C++语言 给出一个坐标集,求以该坐标集为坐标所构成的多边形的外界四边形的四个顶点的全部代码
时间: 2023-04-12 13:01:25 浏览: 87
基于C++编写一个函数求一个4*4二维数组所有周边元素的和
以下是求解给定坐标集构成的多边形外接矩形的 C 代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
double x, y;
} Point;
int cmp(const void *a, const void *b) {
Point *p1 = (Point *)a, *p2 = (Point *)b;
if (p1->x != p2->x) return p1->x < p2->x ? -1 : 1;
return p1->y < p2->y ? -1 : 1;
}
void getBoundingBox(Point *points, int n, Point *minPt, Point *maxPt) {
qsort(points, n, sizeof(Point), cmp);
minPt->x = points[0].x;
maxPt->x = points[n-1].x;
minPt->y = points[0].y;
maxPt->y = points[0].y;
for (int i = 1; i < n; i++) {
if (points[i].y < minPt->y) minPt->y = points[i].y;
if (points[i].y > maxPt->y) maxPt->y = points[i].y;
}
}
int main() {
int n;
printf("请输入坐标点的个数:");
scanf("%d", &n);
Point *points = (Point *)malloc(n * sizeof(Point));
printf("请输入坐标点的 x 和 y 坐标:\n");
for (int i = 0; i < n; i++) {
scanf("%lf %lf", &points[i].x, &points[i].y);
}
Point minPt, maxPt;
getBoundingBox(points, n, &minPt, &maxPt);
printf("外接矩形的四个顶点坐标为:\n");
printf("(%lf, %lf)\n", minPt.x, minPt.y);
printf("(%lf, %lf)\n", maxPt.x, minPt.y);
printf("(%lf, %lf)\n", maxPt.x, maxPt.y);
printf("(%lf, %lf)\n", minPt.x, maxPt.y);
free(points);
return 0;
}
```
注意:以上代码中没有处理输入错误的情况,实际使用时需要加上相应的错误处理代码。
阅读全文