c++已知空间点坐标,求空间形状的重心的代码
时间: 2024-03-21 07:38:50 浏览: 162
以下是求解空间形状重心的 C++ 代码,假设已知空间点的坐标存在一个名为 `points` 的向量中:
```c++
#include <iostream>
#include <vector>
using namespace std;
struct Point {
double x, y, z;
};
Point getCentroid(const vector<Point>& points) {
double sum_x = 0, sum_y = 0, sum_z = 0;
int n = points.size();
for (int i = 0; i < n; ++i) {
sum_x += points[i].x;
sum_y += points[i].y;
sum_z += points[i].z;
}
Point centroid;
centroid.x = sum_x / n;
centroid.y = sum_y / n;
centroid.z = sum_z / n;
return centroid;
}
int main() {
// test example
vector<Point> points = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Point centroid = getCentroid(points);
cout << "Centroid: (" << centroid.x << ", " << centroid.y << ", " << centroid.z << ")" << endl;
return 0;
}
```
这里我们采用了计算几何中的重心计算公式,即将所有点的坐标分别相加再除以点数。本例中假设空间点的坐标为 (x,y,z),用 `Point` 结构体来表示。
阅读全文