ACM100题-001多边形重心问题

来源:互联网 发布:阿里云域名拍卖 编辑:程序博客网 时间:2024/05/13 04:14

题目链接:点击打开链接

参考文章:点击打开链接

描述

在某个多边形上,取N个点,这N个点顺序给出,按照给出顺序将相邻的点用直线连接,最后一个点与第一个点相连,所有线段不与其他线段相交,但是可以重合,可得到一个多边形或一条线段或一个多边形和一个线段的连接后的图形;如果是一条线段,我们定义面积为0,重心坐标为(0,0)。

现在求给出这N个点组成的图形的面积,及重心横纵坐标的和。

输入

第一行有一个整数N(0<N<11),表示这里有N组数据;

每组数据的第一行有一个整数M(M<10000),表示这个多边形有M个顶点。

输出

输出每个多边形的面积、重心横纵坐标的和,小数点后保留三位。

#include<iostream>#include<cstring>#include<cstdio>#include<cmath>#include<algorithm>using namespace std;#define INF 0.0000001const int N = 10010;struct point{double x, y;point():x(0),y(0){}}p[N];int main(){int ncase;scanf("%d", &ncase);while(ncase--){int n;double result = 0;point ans;scanf("%d", &n);                int i;for(i = 0; i < n; ++i)scanf("%lf%lf", &p[i].x, &p[i].y);for(i = 1; i <= n; ++i){double temp = (p[i % n].x * p[i -1].y - p[i % n].y * p[i -1].x) / 2.0;result += temp;ans.x += temp * (p[i % n].x + p[i - 1].x) / 3.0;ans.y += temp * (p[i % n].y + p[i - 1].y) / 3.0;}if(fabs(result - 0) < INF)puts("0.000 0.000");elseprintf("%.3lf %.3lf\n", fabs(result), (ans.x + ans.y) / result); //result取绝对值}return 0;}

上面的代码,如果把i的定义放到了两个for循环里面,在VC里面会报错,报错原因是重复定义变量:error C2374: 'i' : redefinition; multiple initialization

而如果把i的定义放到两个for循环上面,提前定义好,这样for循环里就不用再定义了,也就不会报错了。

例题的结果


Your dream is not what you find in your sleep but what makes you not sleep.


0 0
原创粉丝点击