三角形面积计算(海伦公式或叉积绝对值的一半)

#include <iostream>
#include <cmath>

using namespace std;

struct Point
{
    float x; 
    float y;
    Point(float a, float b) : x(a), y(b)
    {
    }
};

double Length(Point & A, Point & B)
{
    return sqrt(pow(A.x - B.x, 2) + pow(A.y - B.y, 2));
}

double Area1(Point & A, Point & B, Point & C)
{
    double a, b, c;
    a = Length(A, B);
    b = Length(B, C);
    c = Length(C, A);
    double p = (a + b + c) / 2;
    return sqrt((p - a) * (p - b) * (p - c) * p);//海伦公式计算三角形面积
}

double CrossProduct(Point & v1, Point & v2)
{
    return v1.x * v2.y - v1.y * v2.x;
}

int main()
{

    Point A(10, 2);
    Point B(3, 4);
    Point C(5, 7);

    Point v1(B.x - A.x, B.y - A.y);  //向量AB
    Point v2(C.x - A.x, C.y - A.y);  //向量AC


    cout << CrossProduct(v1, v2) << endl;
    cout << Area1(A, B, C) << endl;

    return 0;
}

posted on 2016-10-03 00:58  lakeone  阅读(1855)  评论(0编辑  收藏  举报

导航