错误代码:
#include<stdio.h>
#include<math.h>
int main()
{
int x[102],y[102];
int i,n;
float s,a,b,c,p;
while(scanf("%d",&n)!=EOF&&n)
{
for(i=0;i<n;i++)
scanf("%d%d",&x[i],&y[i]);
s=0;
for(i=2;i<n;i++)
{
a=sqrt((x[0]-x[i-1])*(x[0]-x[i-1])+(y[0]-y[i-1])*(y[0]-y[i-1]));
b=sqrt((x[i-1]-x[i])*(x[i-1]-x[i])+(y[i-1]-y[i])*(y[i-1]-y[i]));
c=sqrt((x[0]-x[i])*(x[0]-x[i])+(y[0]-y[i])*(y[0]-y[i]));
p=(a+b+c)/2;
s+=sqrt(p*(p-a)*(p-b)*(p-c));
}
printf("%.1f\n",s);
}
return 0;
}
未考虑凹多边形的情况 。
正确代码:
#include <stdio.h> struct point { int x; int y; } p[101]; int main() { int n, i, k; double area; while (scanf("%d", &n) != EOF && n != 0) { area = 0.0; k = n; for (i = 0; i < n; i++) { scanf("%d%d", &p[i].x, &p[i].y); } for (i = 0; i < k-1; i++) { area = area + 0.5 * (p[i].x * p[i+1].y - p[i+1].x * p[i].y); } area = area + 0.5 * (p[k-1].x * p[0].y - p[0].x * p[k-1].y); printf("%.1lf\n", area); } return 0; } |