1. 程式人生 > 其它 >C++:使用類方法根據四點計算四面體體積

C++:使用類方法根據四點計算四面體體積

技術標籤:C++學習c++

一個四面體有四個點,分別為a = (x1, y1, z1), b = (x2, y2, z2), c = (x3, y3, z3), 以及d = (x4, y4, z4),計算該四面體的體積。

(1)四面體計算公式 v = \frac{\left |(a-d)\cdot ((b-d)\times (c-d)) \right |}{6}

(2)三維空間的兩點的點乘 a\cdot b = x1*x2 + y1*y2 + z1*z2

(3)三維空間的兩點的叉乘 a\times b = (y1*z2-z1*y2, z1*x2-x1*z2, x1*y2-y1*x2)

方法一:定義一個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-d
    Point p_ad(a.x-d.x, a.y-d.y, a.z-d.z);
    // b-d
    Point p_bd(b.x-d.x, b.y- d.y, b.z-d.z);
    // c-d
    Point 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 result
    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()
{
    // test
    Point 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()
{
    // test
    Point 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;

}