废话不多说,看代码:
#include <iostream>
#include <math.h>
using namespace std;
class Area
{
public:
void In();
void Calucate();
void Out();
private:
int N;
float sum;
float x1,x2,x3,y1,y2,y3;
};
void Area::In()
{
sum = 0;
cout << "输入多边形顶点数:" ;
cin >> N;
cout << "输入坐标按多边形顶点的顺时针或逆时针输入!" << endl;
if(N==3)
{
cout << "请输入第1个顶点坐标:";
cin >> x1 >> y1;
cout << "请输入第2个顶点坐标:";
cin >> x2 >> y2;
cout << "请输入第3个顶点坐标:";
cin >> x3 >> y3;
Calucate();
}else
{
cout << "请输入第1个顶点坐标:";
cin >> x1 >> y1;
cout << "请输入第2个顶点坐标:";
cin >> x2 >> y2;
cout << "请输入第3个顶点坐标:";
cin >> x3 >> y3;
Calucate();
for(int i=3;i<N;i++)
{
cout << "请输入第" << i+1 << "个顶点坐标:";
if((i+1)%2==0)
{
cin >> x2 >> y2;
Calucate();
}else
{
cin >> x3 >> y3;
Calucate();
}
}
}
}
void Area::Calucate()
{
float Cir,L1,L2,L3;
L1 = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
L2 = sqrt((x1-x3)*(x1-x3)+(y1-y3)*(y1-y3));
L3 = sqrt((x2-x3)*(x2-x3)+(y2-y3)*(y2-y3));
Cir = (L1+L2+L3)/2;
sum += sqrt(Cir*(Cir-L1)*(Cir-L2)*(Cir-L3));
}
void Area::Out()
{
cout << "该多边形面积为:" << sum << endl;
}
int main()
{
Area polygon;
polygon.In();
polygon.Out();
return 0;
}
不过该方法有个缺陷就是输入多边形顶点坐标时必须按顺时针或者逆时针输入,不然的话就会计算错误。

