详细参考:http://www.cnblogs.com/jbelial/archive/2011/08/08/2131165.html讲的很详细,很有用
刚开始 在写重心x,y时,将除以3放在这里
x+=(x0+x1+x2)*are/3;
y+=(y0+y1+y2)*are/3;
交了两遍都是WA,后来改成最后结果除以3 ,就A了,原来是中间除以三取精度时在最后结果可能有误差,以后要注意取精度的计算
1 #include<stdio.h> 2 int main() 3 { 4 int t,n,i; 5 double x0,x1,x2,y0,y1,y2; 6 double are,sum; 7 double x,y; 8 scanf("%d",&t); 9 while(t--) 10 { 11 scanf("%d",&n); 12 scanf("%lf%lf%lf%lf",&x0,&y0,&x1,&y1); 13 sum=0;x=y=0; 14 for(i=2;i<n;i++) 15 { 16 scanf("%lf%lf",&x2,&y2); 17 are=0.5*((x1-x0)*(y2-y0)-(x2-x0)*(y1-y0)); 18 x+=(x0+x1+x2)*are; 19 y+=(y0+y1+y2)*are; 20 sum+=are; 21 x1=x2; 22 y1=y2; 23 } 24 printf("%.2f %.2f ",x/sum/3,y/sum/3); 25 } 26 return 0; 27 }