给定地球的两个经纬度坐标,问这两个点的球面距离和直线距离的差。假设地球为球体,半径为6371009米。
代码1:
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
const double PI = acos(-1);
const double R = 6371009;
//角度转化为弧度
double torad(double deg)
{
return deg / 180 * PI;
}
//经纬度(角度)转化为空间坐标
// lat 纬度
// lng 经度
void get_coord(double R, double lat, double lng, double &x, double &y, double &z)
{
lat = torad(lat);
lng = torad(lng);
x = R * cos(lat) * cos(lng);
y = R * cos(lat) * sin(lng);
z = R * sin(lat);
}
//x1,x2是纬度
//y1,y2是经度
double dis(double R, double x1, double y1, double x2, double y2)
{
double a1, b1, a2, b2, c1, c2;
get_coord(R, x1, y1, a1, b1, c1);
get_coord(R, x2, y2, a2, b2, c2);
return sqrt((a1 - a2) * (a1 - a2) + (b1 - b2) * (b1 - b2) + (c1 - c2) * (c1 - c2));
}
int main()
{
int T;
scanf("%d", &T);
double x1, y1, x2, y2;
while(T--)
{
scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
double d1, d2;
d1 = dis(R, x1, y1, x2, y2);
d2 = 2 * R * asin(d1 / (2 * R));
int dif = (int)(d2 - d1 + 0.5);
printf("%d\n", dif);
}
return 0;
}
代码2:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
double r = 6371009;
double p = acos(-1.0);
int n;
double l1,d1,l2,d2;
scanf("%d",&n);
while ( n -- ) {
scanf("%lf%lf%lf%lf",&l1,&d1,&l2,&d2);
l1 *= p/180.0; l2 *= p/180.0;
d1 *= p/180.0; d2 *= p/180.0;
double d = r*sqrt(2-2*(cos(l1)*cos(l2)*cos(d1-d2)+sin(l1)*sin(l2)));
printf("%.0lf\n",2*asin(d/(2*r))*r-d);
// printf("%.0lf\n",d);
}
return 0;
}