1034:计算三角形面积

发布于:2022-11-09 ⋅ 阅读:(478) ⋅ 点赞:(0)

1034:计算三角形面积

【题目描述】

平面上有一个三角形,它的三个顶点坐标分别为(x1,y1),(x2,y2),(x3,y3)(x1,y1),(x2,y2),(x3,y3),那么请问这个三角形的面积是多少,精确到小数点后两位。

【输入】

输入仅一行,包括6个单精度浮点数,分别对应x1,y1,x2,y2,x3,y3。

【输出】

输出也是一行,输出三角形的面积,精确到小数点后两位。

【输入样例】

0 0 4 0 0 3

【输出样例】

6.00


此题给出了平面上三角形三个顶点的坐标,求此三角形的面积。

其中求三角形面积可以使用海伦公式
S = p ( p − a ) ( p − b ) ( p − c ) S=\sqrt {p(p-a)(p-b)(p-c)} S=p(pa)(pb)(pc)

公式中的 p p p是三角形的半周长,即
p = a + b + c 2 p= \frac{a+b+c}2 p=2a+b+c

于是可以写出如下计算三角形面积的函数:

double Heron(double a, double b, double c)
{
    double p = (a+b+c)/2;
    
    return sqrt(p*(p-a)*(p-b)*(p-c));
}

此时只需要通过两点间距离公式得出三角形的三边长 a a a, b b b, c c c
∣ A B ∣ = ( x A − x B ) 2 + ( y A − y B ) 2 |AB|=\sqrt{(x_A-x_B)^2+(y_A-y_B)^2} AB=(xAxB)2+(yAyB)2

于是可以写出如下计算三角形三边长的函数:

double Distance(struct point A, struct point B)
{
    return sqrt((A.x-B.x)*(A.x-B.x) + (A.y-B.y)*(A.y-B.y));
}

最后得到三角形面积。

完整代码如下:

#include <cstdio>
#include <cmath>

struct point
{
    double x, y;
};

double Heron(double a, double b, double c)
{
    double p = (a+b+c)/2;
    
    return sqrt(p*(p-a)*(p-b)*(p-c));
}

double Distance(struct point A, struct point B)
{
    return sqrt((A.x-B.x)*(A.x-B.x) + (A.y-B.y)*(A.y-B.y));
}

int main()
{
    struct point A, B, C;
    double S;
	
    scanf("%lf %lf %lf %lf %lf %lf", &A.x, &A.y, &B.x, &B.y, &C.x, &C.y);
	
    S = Heron(Distance(A, B), Distance(B, C), Distance(A, C));
	
    printf("%.2f", S);
	
    return 0;
}
本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到