1

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?!

4

1 回答 1

3

dlat不具有 0.0 的值。 打印时使用%e%f,而不是查看差异。

将数字与 0.0 进行比较,dlat == 0.0 得到与 相同的结果dlat == -0.0。无需同时进行两个比较。


更多关于 -0
0.0 和 -0.0 具有相同的数值,并且在六个比较运算符 >=、>、==、!=、<、<= 中相互比较。

如果必须区分零,可以使用int signbit()or memcmp()。存在许多方法。

于 2013-08-13T05:12:55.257 回答