I started but didn't realise it was supposed to be C++. Oops, oh well. I didn't finish anyway, it seems like there is information missing from the problem description and I ended up in a big mess :/
But here's the start anyway
Code:
#include <stdio.h>
#include <math.h>
#define PI_DIV_180 0.01745329251994329576923690768489
#define DEG_TO_RAD(a) ((a) * PI_DIV_180)
#define EARTH_RADIUS 6371 /* Approximate radius of the earth in km */
struct GeoCoord {
double lat, lon;
};
/* Convert latitude and longitude supplied in decimal degrees to radians
*/
struct GeoCoord *geo_toRadians(struct GeoCoord *p)
{
p->lat = DEG_TO_RAD(p->lat);
p->lon = DEG_TO_RAD(p->lon);
return p;
}
/* Calculate the great circle distance between two lat/long coords.
* Latitude and longitude for each point must be in radians.
* No error checking is performed.
*/
double geo_distance(const struct GeoCoord *p1, const struct GeoCoord *p2)
{
/* https://en.wikipedia.org/wiki/Haversine_formula
* https://en.wikipedia.org/wiki/Great-circle_distance
*/
double delta_lat, delta_lon,
a, b, c;
delta_lat = p2->lat - p1->lat;
delta_lon = p2->lon - p1->lon;
a = sin(delta_lat / 2); a *= a;
b = sin(delta_lon / 2); b *= b;
c = a + b * cos(p1->lat) * cos(p2->lat);
c = 2 * atan2(sqrt(c), sqrt(1 - c));
return c * EARTH_RADIUS;
}
int main(void)
{
struct GeoCoord tree1 = { 51.5074, -0.1278 };
struct GeoCoord tree2 = { 52.5200, 13.4050 };
printf("Distance %.2f metres\n", geo_distance(geo_toRadians(&tree1), geo_toRadians(&tree2))*1000);
return 0;
}
EDIT: I guess I should ask. Is this assignment meant for a beginner?