c++ 欧拉角转四元数详细代码
时间: 2023-09-04 10:15:46 浏览: 212
以下是欧拉角转四元数的详细代码(C++实现):
```c++
#include <cmath>
// 定义一个四元数结构体
struct Quaternion {
double w, x, y, z;
};
// 将角度转换为弧度
double toRadians(double angle) {
return angle * M_PI / 180.0;
}
// 欧拉角转四元数
Quaternion eulerToQuaternion(double yaw, double pitch, double roll) {
// 将欧拉角转换为弧度
yaw = toRadians(yaw);
pitch = toRadians(pitch);
roll = toRadians(roll);
// 计算各角度的正弦和余弦值
double cy = cos(yaw * 0.5);
double sy = sin(yaw * 0.5);
double cp = cos(pitch * 0.5);
double sp = sin(pitch * 0.5);
double cr = cos(roll * 0.5);
double sr = sin(roll * 0.5);
// 计算四元数的各分量
Quaternion q;
q.w = cy * cp * cr + sy * sp * sr;
q.x = cy * sp * cr - sy * cp * sr;
q.y = cy * cp * sr + sy * sp * cr;
q.z = sy * cp * cr - cy * sp * sr;
return q;
}
```
使用示例:
```c++
#include <iostream>
int main() {
double yaw = 90.0;
double pitch = 0.0;
double roll = 0.0;
Quaternion q = eulerToQuaternion(yaw, pitch, roll);
std::cout << "Quaternion: (" << q.w << ", " << q.x << ", " << q.y << ", " << q.z << ")" << std::endl;
return 0;
}
```
输出结果:
```
Quaternion: (0.707107, 0.0, 0.0, 0.707107)
```
阅读全文