C++判断是否为一个凹多边形
今天的课程中,学习了c++的vector,指针,深复制与浅复制,字符串几个内容,上机作业为:
在之前编写的Point类等的基础上,编写函数bool isConvex(const vector
&points),判断输入的点数组是否是凸多边形,若是返回true,否则返回false。在主函数中输入点的坐标。
非常简单的一段代码,但是在上手之前并不知道该如何判断是否是一个凹多边形,经过查找资料,发现可以通过使用叉乘的方式进行判断。
主要思路为:通过顺时针进行对点的输入,检测多边形上是否有凹点,如果没有则为凸多边形。
其原理是,凸多边形的每个顶点的转向都应该一致,不一致的点 就是凹点。
再来复习一下叉乘:
p1(x1,y1) p2(x2,y2) p3(x3,y3) L1=(x1-x3,y1-y3) L2=(x2-x3,y2-y3) 公式:s=(x1-x3)(y2-y3)-(x2-x3)(y1-y3) 当s>0时,p1,p2,p3三个点呈逆时针
当s<0时,p1,p2,p3三个点呈顺时针
编写过程中,考虑到很多情况下输入的时候并没有考虑是顺时针输入还是逆时针输入,输入的角度可能是外角也可能是内角,因此从单独一个角进行判断并不方便,所以我根据相邻两个角的角度是否一个发生突变进行判断
#pragma once
//point.h
#pragma once
#include<iostream>
#include<vector>
using namespace std;
class point {
public:
point(double nx = 0.0, double ny = 0.0) :x(nx), y(ny) {}
point(point& np);
double GetX() { return x; }
double GetY() { return y; }
void SetX(double nx) { x = nx; }
void SetY(double ny) { y = ny; }
~point() {}//析构
bool isConvex(const vector<point>& points,int number);
private:
double x, y;
};
//point.h
#include<iostream>
#include"point.h"
#include<vector>
point::point(point& p)
{
x = p.x;
y = p.y;
}
bool point::isConvex(const vector<point>& points, int number)
{
//利用叉乘来判断相邻两条边是否为向同一方向旋转,若出现旋转方向不同,则为凹多边形
double CrossProduct ;
vector<int >arr(100);
arr[0] = 1;
//处理从第一个角到最后第三个角的叉乘
for (int i = 0; i < number - 2; i++)
{
CrossProduct = (points[0 + i].x - points[2 + i].x) * (points[1 + i].y - points[2 + i].y) - (points[i + 1].x - points[i + 2].x) * (points[i + 0].y - points[i + 2].y);
arr[i] = CrossProduct;
}
//额外处理最后两个角度的叉乘
CrossProduct = (points[number-2].x - points[0].x) * (points[number-1].y - points[0].y) - (points[number-1].x - points[0].x) * (points[number-2].y - points[0].y);
arr[number-2] = CrossProduct;
CrossProduct = (points[number - 1].x - points[1].x) * (points[0].y - points[1].y) - (points[0].x - points[1].x) * (points[number - 1].y - points[1].y);
arr[number - 1] = CrossProduct;
//若相邻三边之间角度发生改变,则为凹多边形
for (int i = 0; i < number - 2; i++)
{
if (arr[i] * arr[i + 1] < 0)
return false;
}
return true;
}
#include<iostream>
#include<vector>
#include"point.h"
using namespace std;
int main()
{
int n;
double x1, y1;
cout << "please put in the number of points" << endl;
cin >> n;
vector<point>points(n);
cout <<"please put in the points" << endl;
for (int i = 0; i < n; i++)
{
cin >> x1 >> y1;
points[i].SetX(x1);
points[i].SetY(y1);
}
if (points[0].isConvex(points, n))
{
cout << "convex!" << endl;
}
else
{
cout << "concave!" << endl;
}
}