使用Harversine Forumla在C ++中获得错误的结果

时间:2017-12-12 22:00:59

标签: c++ function

我正在尝试使用我的编程作业的半字形公式来计算伦敦和曼彻斯特之间的距离。

给定的公式是

To calculate the distance between two places knowing their latitudes lat1 and 
lat2 and longitudes long1 and long2:
Convert all latitudes and longitudes from degrees to radians, then:
dLat = lat2 - lat1
dLong = long2 - long1
a = sin^2(dLat/2) + cos(lat1)*cos(lat2)*sin^2(dLong/2)
c = 2 * atan2(sqrt(a), sqrt(1-a))
distance = R * c
where R is the radius of the Earth, 3958.75 miles.
Check: you should find the distance between Manchester and London to be 162.66 miles.

我的代码是

double hav_formula(double lat1, double long1, double lat2, double long2){
    // Haversine Formula
    // Calculates distance between two places
    double dlat, dlong, a, c, distance;
    dlat = (lat2 - lat1) / 180 * PI;
    dlong = (long2 - long1) / 180 * PI;
    a = pow(sin(dlat/2),2) + (cos(lat1) * cos(lat2) * pow(sin(dlong/2),2));
    c = 2. * atan2(sqrt(a),sqrt(1-a));
    distance = 3958.75 * c;
    return distance;
}

    double man_lon_distance;
    man_lon_distance = hav_formula(53.48095,-2.23743,51.50853,-0.12574);
    cout<<man_lon_distance<<endl;

我的值为108.342而不是162.66。我做错了什么?

1 个答案:

答案 0 :(得分:0)

我认为你忽略了将每一个纬度/长度护理成弧度......

请在下面找到其他临时变量radLat1/2,另外我在您的计算中添加了一个括号,这些很容易被误解,并且您会得到意想不到的结果。

double hav_formula(double lat1, double long1, double lat2, double long2){
    // Haversine Formula
    // Calculates distance between two places
    double dlat, dlong, a, c, distance;
    double radLat1, radLat2;
    dlat = ((lat2 - lat1) / 180) * PI;
    dlong = ((long2 - long1) / 180) * PI;
    radLat1 = (lat1 / 180) * PI;
    radLat2 = (lat2 / 180) * PI;
    a = pow(sin(dlat/2),2) + (cos(radLat1) * cos(radLat2) * pow(sin(dlong/2),2));
    c = 2. * atan2(sqrt(a),sqrt(1-a));
    distance = 3958.75 * c;
    return distance;
}