c++点是否存在多边形内
时间: 2023-08-11 19:33:07 浏览: 94
以下是一个简单的 C++ 实现,假设多边形的顶点按照顺时针顺序给出:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
const int MAXN = 10010; // 多边形的最大顶点数
struct Point {
double x, y;
};
Point poly[MAXN]; // 多边形的顶点
int n; // 多边形的顶点数
// 判断点 p 是否在多边形内部
bool isInside(Point p) {
int cnt = 0;
for (int i = 0; i < n; i++) {
Point a = poly[i], b = poly[(i + 1) % n];
if (a.y == b.y) continue; // 忽略水平的边
if (p.y < min(a.y, b.y) || p.y >= max(a.y, b.y)) continue; // 忽略不相交的边
double x = (p.y - a.y) * (b.x - a.x) / (b.y - a.y) + a.x;
if (x >= p.x) cnt++; // 统计相交的边数
}
return cnt % 2 == 1; // 如果相交的边数为奇数,则在多边形内部
}
int main() {
// 读入多边形的顶点
cin >> n;
for (int i = 0; i < n; i++) {
cin >> poly[i].x >> poly[i].y;
}
// 判断若干个点是否在多边形内部
int m;
cin >> m;
for (int i = 0; i < m; i++) {
Point p;
cin >> p.x >> p.y;
if (isInside(p)) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
}
return 0;
}
```
此代码假设多边形的顶点已经按照顺时针顺序给出,如果多边形的顶点按照逆时针顺序给出,需要在 `isInside` 函数中将统计相交的边数的条件改为 `if (x < p.x) cnt++;`。
阅读全文
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)