Can't compare two CLLocationCoordinate2Ds (negative zero??)

﹥>﹥吖頭↗ 提交于 2019-12-11 06:53:20

问题


I'm having the hardest time comparing two (what should be identical) CLLocationCoordinate2D structs in my iOS app. For some reason no matter how I compare them, the latitude just won't say it's equal.

The code:

double dlat = self.mapView.centerCoordinate.latitude - self.centerOnNextView.coordinate.latitude;
double dlong = self.mapView.centerCoordinate.longitude - self.centerOnNextView.coordinate.longitude;
NSLog(@"dlat: %f dlong: %f, dlat == 0.0: %d, dlat == -0.0: %d, dlong == 0.0: %d, dlong == -0.0: %d",
    dlat, dlong, dlat == 0.0, dlat == -0.0, dlong == 0.0, dlong == -0.0);
if ( ( dlat == 0.0 || dlat == -0.0 ) && ( dlong == 0.0 || dlong == -0.0 ) ) {
    NSLog(@"WE ARE EQUAL!");
}

I even tried if ( [@(dlat) isEqualToNumber:@(0)] && [@(dlong) isEqualToNumber:@(0)] ) as the comparison check, but it failed too.

Here's the output:

dlat: -0.000000
dlong: 0.000000
dlat == 0.0: 0 (false)
dlat == -0.0: 0 (false)
dlong == 0.0: 1 (true)
dlong == -0.0: 1 (true)

For some reason I just keep getting that negative zero in there and nothing will compare against it. What the heck can I do to get these things to compare?!


回答1:


dlat does not have the value of 0.0. Use %e when printing instead of %f to see the difference.

Comparing a number to 0.0 as in dlat == 0.0 gets the same result as dlat == -0.0. No need to do both compares.


More on -0
0.0 and -0.0 have the same numeric value and compare just like each other in the six compare operators >=, >, ==, !=, <, <=.

If one must distinguish between the zeros, one could use int signbit() or memcmp(). Many methods exist.



来源:https://stackoverflow.com/questions/18200609/cant-compare-two-cllocationcoordinate2ds-negative-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!