最终AC代码如下:
#include <cstdio> typedef struct point{ int x, y; }; double getArea(point a, point b){ return a.x*b.y - a.y*b.x; //此处为什么不需要绝对值??? } int main(){ int i, n; point p[101]; double ans; while(scanf("%d", &n) && n) { for(i=0; i<n; i++){ scanf("%d %d", &(p[i]).x, &(p[i]).y); if(i > 0){ p[i].x -= p[0].x; //以p[0]为公共点 p[i].y -= p[0].y; } } ans = 0; for(i=1; i<n-1; i++) ans += getArea(p[i], p[i+1]); printf("%.1lf\n", ans/2); } return 0; }
主要参考资料:
总结:用向量叉积的形式求面积,我倒真的没想过,第一反应就是采用海伦公式解,但是通不过。不知道是不是测试用例的问题~另一个疑惑点是,向量叉积是有正负的,虽然顶点是按逆时针方向排列的,返回值一定是正的,但是为什么我返回前加上fabs()函数后,在OJ上反而不能通过了呢?这个问题目前没有想明白,写下来先记录吧。
关于用海伦的写法如下:(不知道是算法本身存在问题,还是所采用的测试用例不能用海伦来解?)
#include <bits/stdc++.h> using namespace std; typedef long long int LL; //用海伦公式不能通过! //由三边 求三角形面积 => 海伦公式 //p = (a+b+c)/2; //S = sqrt(p*(p-a)*(p-b)*(p-c)); int main(){ double p, t1, t2, t3, ans; LL i, n, a, b; vector<double> vd; vector<pair<LL, LL> > vp; while(scanf("%lld", &n), n!=0){ vp.clear(); for(i=0; i<n; i++){ scanf("%lld %lld", &a, &b); vp.push_back(make_pair(a, b)); } vd.clear(); for(i=0; i<n; i++){ a = (vp[(i+1)%n]).first - (vp[i]).first; b = (vp[(i+1)%n]).second - (vp[i]).second; vd.push_back(sqrt(1.0*(a*a+b*b))); } ans = 0; t1 = vd[0]; for(i=2; i<vd.size(); i++){ t2 = vd[i-1]; a = (vp[0]).first - (vp[i]).first; b = (vp[0]).second - (vp[i]).second; t3 = sqrt(1.0 * (a*a + b*b)); p = (t1 + t2 + t3) / 2; ans += sqrt(p * (p-t1) * (p-t2) * (p-t3)); t1 = t3; } printf("%.1lf\n", ans); } return 0; }
原文:https://www.cnblogs.com/heyour/p/12559688.html