C++ 判断一个多边形是否为矩形
时间: 2024-06-13 22:06:06 浏览: 257
以下是判断一个多边形是否为矩形的C++代码:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Point {
int x, y;
Point(int x = 0, int y = 0) :x(x), y(y) {}
};
typedef Point Vector;
Vector operator-(Point A, Point B) {
return Vector(A.x - B.x, A.y - B.y);
}
int Cross(Vector A, Vector B) {
return A.x * B.y - A.y * B.x;
}
int Area2(Point A, Point B, Point C) {
return Cross(B - A, C - A);
}
bool IsRectangle(vector<Point>& p) {
int n = p.size();
if (n != 4) return false;
for (int i = 0; i < n; i++) {
if (Area2(p[i], p[(i + 1) % n], p[(i + 2) % n]) == 0) {
Vector v1 = p[(i + 1) % n] - p[i];
Vector v2 = p[(i + 2) % n] - p[(i + 1) % n]; if (v1.x * v2.x + v1.y * v2.y != 0) return false;
}
}
return true;
}
int main() {
vector<Point> p;
p.push_back(Point(0, 0));
p.push_back(Point(0, 1));
p.push_back(Point(1, 1));
p.push_back(Point(1, 0));
if (IsRectangle(p)) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
return 0;
}
```
阅读全文