nyoj 67-三角形面积 (海伦公式, 叉积)

67-三角形面积


内存限制:64MB 时间限制:3000ms 特判: No
通过数:8 提交数:13 难度:2

题目描述:

给你三个点,表示一个三角形的三个顶点,现你的任务是求出该三角形的面积

输入描述:

每行是一组测试数据,有6个整数x1,y1,x2,y2,x3,y3分别表示三个点的横纵坐标。(坐标值都在0到10000之间)
输入0 0 0 0 0 0表示输入结束
测试数据不超过10000组

输出描述:

输出这三个点所代表的三角形的面积,结果精确到小数点后1位(即使是整数也要输出一位小数位)

样例输入:

0 0 1 1 1 3
0 1 1 0 0 0
0 0 0 0 0 0

样例输出:

1.0
0.5

分析:
  方法一、海伦公式 s = sqrt(p*(p-a)*(p-b)*(p-c)), p = (a+b+c)/2;
  方法二、叉积 s = fabs(BA(x)*CA(y) - BA(y)*CA(x)) / 2.0

方法一(海伦公式)(AC):
 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstring>
 4 #include <cstdio>
 5 #include <cmath>
 6 #include <stack>
 7 #include <map>
 8 #include <queue>
 9 #include <set>
10 
11 using namespace std;
12 
13 int main()
14 {
15     double a, b, c, d, e, f;
16     while(scanf("%lf%lf%lf%lf%lf%lf", &a, &b, &c, &d, &e, &f), a || b || c || d || e || f)
17     {
18         double line_a = sqrt((a-c)*(a-c) + (b-d)*(b-d));
19         double line_b = sqrt((a-e)*(a-e) + (b-f)*(b-f));
20         double line_c = sqrt((c-e)*(c-e) + (d-f)*(d-f));
21         double line_p = (line_a + line_b + line_c) / 2;
22         printf("%.1lf\n", sqrt(line_p * (line_p - line_a)* (line_p - line_b)* (line_p - line_c))); // 海伦
23     }
24     return 0;
25 }

方法二(叉积)(AC):

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstring>
 4 #include <cstdio>
 5 #include <cmath>
 6 #include <stack>
 7 #include <map>
 8 #include <queue>
 9 #include <set>
10 
11 using namespace std;
12 struct node
13 {
14     double x, y;
15 };
16 
17 double cross_product(node a, node b, node c)
18 {
19     return ((b.x-a.x)*(c.y-a.y) - (b.y-a.y)*(c.x-a.x));
20 }
21 
22 int main()
23 {
24     node a, b, c;
25     while(scanf("%lf%lf%lf%lf%lf%lf", &a.x, &a.y, &b.x, &b.y, &c.x, &c.y), a.x || a.y || b.x || b.y || c.x || c.y)
26     {
27         printf("%.1lf\n", fabs(cross_product(a, b, c)) / 2.0);
28     }
29     return 0;
30 }

猜你喜欢

转载自www.cnblogs.com/GetcharZp/p/9110974.html