Function SOMETIMES returns incorrect value

Hello, for a project I made, I am using a function that determines the distance between two places on a map based on their latitude and longitude, returning their distance in miles. However, we were given examples of correct comparisons, and some of them I get right, others I do not.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 double calculateDifference(double lat1, double lon1, double lat2, double lon2)
{

  
  
  double dlon;
  double dlat;
  double a, c, r, distance;
  r = 3959.9;
  double pi = 3.14159265;

  
  dlat = (lat1 - lat2);
  dlon = (lon1 - lon2);

  a = pow(sin(((dlat*pi/180)/2)),2) + cos(lat1*pi/180) * cos(lat2*pi/180)
    * pow(sin(((dlon*pi/180)/2)),2);
  c = 2 * atan2(sqrt(a), sqrt(1 - a));
    distance = r * c;
   
    return distance; 

}


This is how the function should be written. When I put in the location for say, LAX and Kahului Airport, I get the correct miles back (2483.3)

But when I put in LAX and compare it to Sao Paolo, I get back like 5000 miles, when it should be (6164.9)
Last edited on
Seems to work fine for me.
distance between (33.9416, -118.409) and (-23.5505, -46.6333) = 6161.77 miles


If you use constants, declare them as const.
 
const double r{ 3959.9 }, pi{ 3.14159265 };


It's always a good idea to keep variables of the same type together and to initialise them.
 
double dlon{}, dlat{}, a{}, c{}, distance{};


This piece of code is unreadable, with all the parentheses.
1
2
  a = pow(sin(((dlat*pi/180)/2)),2) + cos(lat1*pi/180) * cos(lat2*pi/180)
    * pow(sin(((dlon*pi/180)/2)),2);

I'd recommend you do something like this:
1
2
3
4
5
6
7
dlat = (lat1-lat2) * pi/180;
dlon = (lon1-lon2) * pi/180;
    
lat1 *= pi/180;
lat2 *= pi/180;

a = pow( sin( dlat/2 ), 2 ) + cos( lat1 ) * cos( lat2 ) * pow( sin( dlon/2 ), 2 );

This makes the code much more readable, especially when you're debugging.

Maybe use an array or class/struct to store each of the latitude/longitudes?
double calcDist( double lat1, double lon1, double lat2, double lon2 )
1
2
3
4
5
6
7
8
9
10
11
double calcDist( const double from[2], const double to[2] )
{
    // ...
}

int main()
{
    const double pos1[]{ 33.9416, -118.4085 }, pos2[]{ -23.5505, -46.6333 };
    
    std::cout << "distance between (" << pos1[0] << ", " << pos1[1] << ") and (" << pos2[0] << ", " << pos2[1] << ") = " << calcDist( pos1, pos2 ) << " miles\n";
}
Last edited on
Topic archived. No new replies allowed.