1. 程式人生 > >求三角形面積三種方式

求三角形面積三種方式

#include <math.h>
struct point{double x,y;};

//計算cross product (P1-P0)x(P2-P0)
double xmult(point p1,point p2,point p0){
    return (p1.x-p0.x)*(p2.y-p0.y)-(p2.x-p0.x)*(p1.y-p0.y);
}
double xmult(double x1,double y1,double x2,double y2,double x0,double y0){
    return (x1-x0)*(y2-y0)-(x2-x0)*(y1-y0);
}

//計算三角形面積,輸入三頂點
double area_triangle(point p1,point p2,point p3){ return fabs(xmult(p1,p2,p3))/2; } double area_triangle(double x1,double y1,double x2,double y2,double x3,double y3){ return fabs(xmult(x1,y1,x2,y2,x3,y3))/2; } //計算三角形面積,輸入三邊長 double area_triangle(double a,double b,double c){ double s=(a+b+c)/2
; return sqrt(s*(s-a)*(s-b)*(s-c)); } //計算多邊形面積,頂點按順時針或逆時針給出 double area_polygon(int n,point* p){ double s1=0,s2=0; int i; for (i=0;i<n;i++) s1+=p[(i+1)%n].y*p[i].x,s2+=p[(i+1)%n].y*p[(i+2)%n].x; return fabs(s1-s2)/2; }