基于c++ 求三维 三角形外心 代码
时间: 2023-11-04 18:15:50 浏览: 192
以下是基于C++的求三维三角形外心的代码:
```c++
#include <iostream>
#include <cmath>
using namespace std;
// 三维向量结构体
struct Vector3D {
double x, y, z;
};
// 三角形结构体
struct Triangle {
Vector3D vertex[3];
};
// 计算两个向量的叉积
Vector3D crossProduct(Vector3D v1, Vector3D v2) {
Vector3D result;
result.x = v1.y * v2.z - v1.z * v2.y;
result.y = v1.z * v2.x - v1.x * v2.z;
result.z = v1.x * v2.y - v1.y * v2.x;
return result;
}
// 计算两个向量的点积
double dotProduct(Vector3D v1, Vector3D v2) {
return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
}
// 计算向量的模长
double magnitude(Vector3D v) {
return sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
}
// 计算三角形外心
Vector3D circumcenter(Triangle t) {
Vector3D a = t.vertex[0];
Vector3D b = t.vertex[1];
Vector3D c = t.vertex[2];
Vector3D ab = { b.x - a.x, b.y - a.y, b.z - a.z };
Vector3D ac = { c.x - a.x, c.y - a.y, c.z - a.z };
Vector3D bc = { c.x - b.x, c.y - b.y, c.z - b.z };
double ab2 = dotProduct(ab, ab);
double ac2 = dotProduct(ac, ac);
double bc2 = dotProduct(bc, bc);
Vector3D abXac = crossProduct(ab, ac);
Vector3D abXbc = crossProduct(ab, bc);
Vector3D acXbc = crossProduct(ac, bc);
Vector3D circumcenter = {
(ab2 * acXbc.x + ac2 * abXbc.x + bc2 * abXac.x) / (2 * magnitude(abXac)),
(ab2 * acXbc.y + ac2 * abXbc.y + bc2 * abXac.y) / (2 * magnitude(abXac)),
(ab2 * acXbc.z + ac2 * abXbc.z + bc2 * abXac.z) / (2 * magnitude(abXac))
};
circumcenter.x += a.x;
circumcenter.y += a.y;
circumcenter.z += a.z;
return circumcenter;
}
int main() {
Triangle t;
cout << "Enter the coordinates of the first vertex: ";
cin >> t.vertex[0].x >> t.vertex[0].y >> t.vertex[0].z;
cout << "Enter the coordinates of the second vertex: ";
cin >> t.vertex[1].x >> t.vertex[1].y >> t.vertex[1].z;
cout << "Enter the coordinates of the third vertex: ";
cin >> t.vertex[2].x >> t.vertex[2].y >> t.vertex[2].z;
Vector3D circumcenter = circumcenter(t);
cout << "The coordinates of the circumcenter are: ";
cout << circumcenter.x << " " << circumcenter.y << " " << circumcenter.z << endl;
return 0;
}
```
该代码首先定义了三维向量结构体和三角形结构体,并实现了计算两个向量的叉积、点积和模长的函数。然后实现了计算三角形外心的 `circumcenter` 函数,该函数根据公式计算出三角形外心的坐标。最后在 `main` 函数中读入三角形的三个顶点坐标,调用 `circumcenter` 函数计算出外心坐标,最终输出结果。
阅读全文