判断多边形凸凹

#include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include <iostream>
using namespace std;
struct point {
	int x, y;
}P[100];
int n;//顶点个数

int judge() {
	double angle = 0;//较小角的和
	point a, b;
	a.x = P[1].x - P[0].x; a.y = P[1].y - P[0].y;
	b.x = P[n - 1].x - P[0].x; b.y = P[n - 1].y - P[0].y;
	angle += acos((a.x*b.x + a.y*b.y) / (sqrt(pow(a.x, 2) + pow(a.y, 2))*sqrt(pow(b.x, 2) + pow(b.y, 2))));//第一个角角度求解
	a.x = P[0].x - P[n - 1].x; a.y = P[0].y - P[n - 1].y;
	b.x = P[n - 2].x - P[n - 1].x; b.y = P[n - 2].y - P[n - 1].y;
	angle += acos((a.x*b.x + a.y*b.y) / (sqrt(pow(a.x, 2) + pow(a.y, 2))*sqrt(pow(b.x, 2) + pow(b.y, 2))));//最后一个角角度求解	
	for (int i = 1; i < n - 1; i++) {
		a.x = P[i + 1].x - P[i].x; a.y = P[i + 1].y - P[i].y;
		b.x = P[i - 1].x - P[i].x; b.y = P[i - 1].y - P[i].y;
		angle += acos((a.x*b.x + a.y*b.y) / (sqrt(pow(a.x, 2) + pow(a.y, 2))*sqrt(pow(b.x, 2) + pow(b.y, 2))));
	}//计算所有较小角的和  若等于(n-2)pi 则凸
	cout << angle << endl;
	cout << (n - 2)*acos(-1) << endl;
	if (angle == (n - 2)*acos(-1))printf("凸");
	else printf("凹");
	return 0;
}

int main() {
	scanf_s("%d", &n);
	for (int i = 0; i < n; i++)scanf_s("%d%d", &P[i].x, &P[i].y);
	judge();
	system("pause");
}

每个顶点的较小角(内角或外角)相加,若等于(顶点数-2)*180度,这为凸n边形,若小于,则为凹n边形。

可以用向量求cos值,再用反三角函数就角度,得出来的就是较小角(内角或者外角)。

猜你喜欢

转载自blog.csdn.net/leo_10/article/details/80762617