C++实现——求三角形的面积(海伦公式)

C++实现——求三角形的面积(海伦公式)_第1张图片

//求三角形的面积
/*语法:result = area3(float x1, float y1, float x2, float y2, float x3, float y3);
参数:
x1~3:三角形3个顶点x坐标
y1~3:三角形3个顶点y坐标
返回值:三角形面积
*/
/*
方法:海伦-秦九公式已知三角形三边a,b,c,则S面积= √[p(p - a)(p - b)(p - c)] (海伦公式)
(其中p=(a+b+c)/2)

*/
float area3(float x1, float y1, float x2, float y2, float x3, float y3){

    float a, b, c, p, s;
    //求三边长度
    a = sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));
    b = sqrt((x1 - x3)*(x1 - x3) + (y1 - y3)*(y1 - y3));
    c = sqrt((x2 - x3)*(x2 - x3) + (y2 - y3)*(y2 - y3));

    p = (a + b + c) / 2;
    //求面积
    s = sqrt(p*(p - a)*(p - b)*(p - c));

    return s;

}
//测试函数
int main(){
    float x1, y1, x2, y2, x3, y3;
    while (cin>>x1>>y1>>x2>>y2>>x3>>y3){
        cout << area3(x1, y1, x2, y2, x3, y3);
    }
    return 0;
}

你可能感兴趣的:(algorithm)