C++已知三维空间内三点坐标,求三角形面积

一、算法原理

C++已知三维空间内三点坐标,求三角形面积_第1张图片

二、代码实现

#include 
#include 

using namespace std;
	
	struct Point
	{
     
		double x;
		double y;
		double z;
	};

	//求三角形面积;
	//返回-1为不能组成三角形;
	double count_triangle_area(Point a, Point b, Point c) {
     
		double area = -1;
		double dis;//三角形的高
		double side[3];//存储三条边的长度;

		side[0] = sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2) + pow(a.z - b.z, 2));
		side[1] = sqrt(pow(a.x - c.x, 2) + pow(a.y - c.y, 2) + pow(a.z - c.z, 2));
		side[2] = sqrt(pow(c.x - b.x, 2) + pow(c.y - b.y, 2) + pow(c.z - b.z, 2));

		//不能构成三角形;
		if (side[0] + side[1] <= side[2] || side[0] + side[2] <= side[1] || side[1] + side[2] <= side[0])
			return area;

		//利用海伦公式。s=sqr(p*(p-a)(p-b)(p-c)); 
		double p = (side[0] + side[1] + side[2]) / 2; //半周长;
		area = sqrt(p * (p - side[0]) * (p - side[1]) * (p - side[2]));
		//求AB边上的高
		dis = area / side[0];		
		cout << "三角形的面积:" << area << endl;
		return dis;
		
	}
	
int
main()
{
     
	//输入空间内三点的坐标
	double A1[3] = {
      21.34, 19.16, 0.36 };
	double B1[3] = {
      21.48, 19.7, 0.38 };
	double C1[3] = {
      21.86, 20.09, 0.38 };
	//转换成Point类型
	Point A, B, C;
	A.x = A1[0];
	A.y = A1[1];
	A.z = A1[2];
	
	B.x = B1[0];
	B.y = B1[1];
	B.z = B1[2];

	C.x = C1[0];
	C.y = C1[1];
	C.z = C1[2];
	
	cout << "三角形AB边上的高:" << count_triangle_area(A, B, C)*100 <<"cm" << endl;
}

三、结果展示

在这里插入图片描述

你可能感兴趣的:(C++学习)