C语言/c++代码生成 两个不同的空间坐标系,将一个三维坐标系转化为另一个坐标系,需要的旋转角度为多少(-180~180)
时间: 2024-03-23 20:40:58 浏览: 94
好的,根据你的描述,我可以给出以下 C++ 代码实现:
```c++
#include <iostream>
#include <cmath>
using namespace std;
const double pi = acos(-1.0); // π
// 定义三维向量结构体
struct Vector3 {
double x, y, z;
Vector3(double _x = 0, double _y = 0, double _z = 0) : x(_x), y(_y), z(_z) {}
// 向量叉乘
Vector3 operator*(const Vector3 &v) const {
return Vector3(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x);
}
// 向量标准化
void normalize() {
double len = sqrt(x * x + y * y + z * z);
if (len > 1e-6) {
x /= len;
y /= len;
z /= len;
}
}
// 向量点乘
double operator%(const Vector3 &v) const {
return x * v.x + y * v.y + z * v.z;
}
// 向量长度
double length() const {
return sqrt(x * x + y * y + z * z);
}
// 向量夹角的弧度值
double angle(const Vector3 &v) const {
return acos((*this) % v / length() / v.length());
}
};
// 将角度转换为弧度
double rad(double deg) {
return deg / 180.0 * pi;
}
// 将弧度转换为角度
double deg(double rad) {
return rad / pi * 180.0;
}
// 将三维向量绕指定向量旋转一定角度
Vector3 rotate(const Vector3 &v, const Vector3 &axis, double angle) {
Vector3 res;
double s = sin(rad(angle));
double c = cos(rad(angle));
Vector3 u = axis;
u.normalize();
res.x = (u.x * u.x * (1 - c) + c) * v.x + (u.x * u.y * (1 - c) - u.z * s) * v.y + (u.x * u.z * (1 - c) + u.y * s) * v.z;
res.y = (u.y * u.x * (1 - c) + u.z * s) * v.x + (u.y * u.y * (1 - c) + c) * v.y + (u.y * u.z * (1 - c) - u.x * s) * v.z;
res.z = (u.x * u.z * (1 - c) - u.y * s) * v.x + (u.y * u.z * (1 - c) + u.x * s) * v.y + (u.z * u.z * (1 - c) + c) * v.z;
return res;
}
int main() {
Vector3 v(1, 0, 0); // 待旋转的向量
Vector3 axis(0, 0, 1); // 旋转轴
double angle = 30; // 旋转角度(单位:度)
Vector3 res = rotate(v, axis, angle); // 计算旋转后的向量
cout << "旋转后的向量:" << res.x << " " << res.y << " " << res.z << endl;
return 0;
}
```
其中,`Vector3` 结构体表示三维向量,定义了向量的加、减、点乘、叉乘、标准化等操作。`rotate` 函数用于将向量绕指定轴旋转一定角度,其中采用了 Rodrigues 旋转公式。在 `main` 函数中,我们定义了待旋转的向量 `v`,指定了绕哪个轴(这里是 z 轴)旋转多少度,然后调用 `rotate` 函数计算旋转后的向量。
阅读全文
相关推荐















