写一个笛卡尔坐标系和大地坐标系的相互转换c++代码
时间: 2023-05-17 07:05:16 浏览: 81
以下是一个简单的C代码,用于将笛卡尔坐标系和大地坐标系相互转换:
#include <stdio.h>
#include <math.h>
#define PI 3.14159265358979323846
#define a 6378137.0
#define b 6356752.314245
#define f (a - b) / a
#define e sqrt(2 * f - f * f)
double rad(double d) {
return d * PI / 180.0;
}
void cartesian_to_geodetic(double x, double y, double z, double *lat, double *lon, double *h) {
double p = sqrt(x * x + y * y);
double theta = atan2(z * a, p * b);
double sin_theta = sin(theta);
double cos_theta = cos(theta);
*lat = atan2(z + e * e * b * sin_theta * sin_theta * sin_theta, p - e * e * a * cos_theta * cos_theta * cos_theta);
*lon = atan2(y, x);
double N = a / sqrt(1 - e * e * sin(*lat) * sin(*lat));
*h = p / cos(*lat) - N;
*lat = *lat * 180.0 / PI;
*lon = *lon * 180.0 / PI;
}
void geodetic_to_cartesian(double lat, double lon, double h, double *x, double *y, double *z) {
double N = a / sqrt(1 - e * e * sin(rad(lat)) * sin(rad(lat)));
*x = (N + h) * cos(rad(lat)) * cos(rad(lon));
*y = (N + h) * cos(rad(lat)) * sin(rad(lon));
*z = (N * (1 - e * e) + h) * sin(rad(lat));
}
int main() {
double x = 1000000.0;
double y = 2000000.0;
double z = 3000000.0;
double lat, lon, h;
cartesian_to_geodetic(x, y, z, &lat, &lon, &h);
printf("Cartesian coordinates: (%lf, %lf, %lf)\n", x, y, z);
printf("Geodetic coordinates: (%lf, %lf, %lf)\n", lat, lon, h);
geodetic_to_cartesian(lat, lon, h, &x, &y, &z);
printf("Geodetic coordinates converted back to Cartesian: (%lf, %lf, %lf)\n", x, y, z);
return 0;
}