Description
给出一简单多边形的顶点坐标,求其面积
Input
输入数据包含多个测试实例,每个测试实例占一行,每行的开始是一个整数n(3<=n<=100),它表示多边形的边数(当然也是顶点数),然后是按照逆时针顺序给出的n个顶点的坐标(x1, y1, x2, y2… xn, yn),为了简化问题,这里的所有坐标都用整数表示。输入数据中所有的整数都在32位整数范围内,n=0表示数据的结束,不做处理
Output
对于每个测试实例,请输出对应的多边形面积,结果精确到小数点后一位小数。每个实例的输出占一行
Sample Input
3 0 0 1 0 0 1
4 1 0 0 1 -1 0 0 -1
0
Sample Output
0.5
2.0
Solution
将多边形拆成多个三角形之后累加各三角形有向面积(用叉乘)后取绝对值即可
Code
#include<cstdio>
#include<iostream>
using namespace std;
struct node
{
double x,y;
}pot[111];
int main()
{
int n;
while(scanf("%d",&n),n)
{
for(int i=0;i<n;i++)
cin>>pot[i].x>>pot[i].y;
double ans=0;
for(int i=0;i<n;i++)
{
int j=(i+1)%n;
ans+=pot[i].x*pot[j].y-pot[i].y*pot[j].x;
}
ans/=2;
ans=ans>0?ans:-ans;
printf("%.1lf\n",ans);
}
return 0;
}