|
发表于 2021-12-11 18:53:47
|
显示全部楼层
找到公式了
C 代码:- #include <stdio.h>
- #include <stdlib.h>
- typedef struct{
- int x, y;
- }point;
- double area(int n, point arr[]){
- double res = 0;
- int x, y;
- for(int i = 0; i < n-1; i++){
- x = arr[i].x;
- y = arr[i+1].y;
- res += x*y;
- }
- x = arr[n-1].x;
- y = arr[0].y;
- res += x*y;
- for(int i = 0; i < n-1; i++){
- x = arr[i+1].x;
- y = arr[i].y;
- res -= x*y;
- }
- x = arr[0].x;
- y = arr[n-1].y;
- res -= x*y;
- return .5*abs(res);
- }
- int main()
- {
- point points[7] = {{4, 2}, {2, 6}, {-2, 8}, {-6, 6}, {-8, 4}, {-6, 0}, {-2, -2}};
- printf("%.2lf", area(7, points));
- return 0;
- }
复制代码 输出结果:
Python 代码:- def area(n, arr):
- res = 0
- for i in range(n-1):
- x = arr[i][0]
- y = arr[i+1][1]
- res += x*y
- x = arr[n-1][0]
- y = arr[0][1]
- res += x*y
- for i in range(n-1):
- x = arr[i+1][0]
- y = arr[i][1]
- res -= x*y
- x = arr[0][0]
- y = arr[n-1][1]
- res -= x*y
- return .5*abs(res)
- points = [(4, 2), (2, 6), (-2, 8), (-6, 6), (-8, 4), (-6, 0), (-2, -2)]
- print(area(7, points))
复制代码 输出结果: |
|