一个四面体有四个点,分别为a = (x1, y1, z1), b = (x2, y2, z2), c = (x3, y3, z3), 以及d = (x4, y4, z4),计算该四面体的体积。
(1)四面体计算公式
(2)三维空间的两点的点乘
(3)三维空间的两点的叉乘
方法一:定义一个Point类计算
先定义一个Point类来放点坐标,接着定义一个函数使用Point类型的对象作为参数传入,直接计算体积。
#include <iostream>
#include <math.h>using namespace std;// define a point class to store a point
class Point
{
public:double x;double y;double z;Point(double x, double y, double z);
};
// constructor
Point::Point(double x, double y, double z)
{this->x = x;this->y = y;this->z = z;
}// the function based on the given equation
double cal_volume(Point a, Point b, Point c, Point d)
{// a-dPoint p_ad(a.x-d.x, a.y-d.y, a.z-d.z);// b-dPoint p_bd(b.x-d.x, b.y- d.y, b.z-d.z);// c-dPoint p_cd(c.x-d.x, c.y-d.y, c.z-d.z);// (b-d)x(c-d)Point p_bd_cd(p_bd.y * p_cd.z - p_bd.z * p_cd.y, p_bd.z * p_cd.x - p_bd.x * p_cd.z, p_bd.x * p_cd.y - p_bd.y * p_cd.x);// final resultdouble res = abs(p_ad.x * p_bd_cd.x + p_ad.y * p_bd_cd.y + p_ad.z * p_bd_cd.z) / 6.0;return res;
}int main()
{// testPoint p1(0, 0, 0);Point p2(2, 0, 0);Point p3(0, 2, 0);Point p4(1, 1, 1);double v = cal_volume(p1, p2, p3, p4);cout << v << endl;
}
方法二:定义一个四面体类(tetrahedron),类方法计算
在Point类的基础上,再定义一个tetrahedron类(这个类拥有一个指向Point类型对象的指针,以及指针长度:此处为四面体,有四个点默认为四)。然后通过tetrahedron类对象计算体积,此处的计算体积方法是tetrahedron类的成员函数。
#include <iostream>
#include <vector>
using namespace std;class Point
{
public:double x;double y;double z;Point(double x, double y, double z);
};
// constructor
Point::Point(double x, double y, double z)
{this->x = x;this->y = y;this->z = z;
}class tetrahedron
{
public:tetrahedron(Point *p, int num);double cal_volume();int num_p;Point *p;
};
// constructor
tetrahedron::tetrahedron(Point *tp, int num):num_p(num)
{for(int i = 0; i < this->num_p; i++){this->p[i] = Point(tp[i].x, tp[i].y, tp[i].z);}
}
// function to calculate volume
double tetrahedron::cal_volume()
{Point p_ad(p[0].x-p[3].x, p[0].y-p[3].y, p[0].z-p[3].z);Point p_bd(p[1].x-p[3].x, p[1].y- p[3].y, p[1].z-p[3].z);Point p_cd(p[2].x-p[3].x, p[2].y-p[3].y, p[2].z-p[3].z);Point p_bd_cd(p_bd.y * p_cd.z - p_bd.z * p_cd.y, p_bd.z * p_cd.x - p_bd.x * p_cd.z, p_bd.x * p_cd.y - p_bd.y * p_cd.x);double res = abs(p_ad.x * p_bd_cd.x + p_ad.y * p_bd_cd.y + p_ad.z * p_bd_cd.z) / 6.0;return res;
}
int main()
{// testPoint p1(0, 0, 0);Point p2(2, 0, 0);Point p3(0, 2, 0);Point p4(1, 1, 1);Point *p = new Point(0, 0, 0);p[0]=p1;p[1]=p2;p[2]=p3;p[3]=p4;tetrahedron t(p, 4);double res = t.cal_volume();cout << res << endl;}