1

在阅读有关 location 的 Android 开发人员博客文章时,我遇到了这段代码(从博客中剪切和粘贴):

List<String> matchingProviders = locationManager.getAllProviders();
for (String provider: matchingProviders) {
  Location location = locationManager.getLastKnownLocation(provider);
  if (location != null) {
    float accuracy = location.getAccuracy();
    long time = location.getTime();

    if ((time > minTime && accuracy < bestAccuracy)) {
      bestResult = location;
      bestAccuracy = accuracy;
      bestTime = time;
    }
    else if (time < minTime && 
         bestAccuracy == Float.MAX_VALUE && time > bestTime){
      bestResult = location;
      bestTime = time;
    }
  }
}

虽然其余的都很清楚,但这条线让我很难过:

    else if (time < minTime && 
         bestAccuracy == Float.MAX_VALUE && time > bestTime){

“时间”必须在可接受的延迟期内并且比之前的最佳时间更新。那讲得通。

但是 bestAccuracy 与 Max Float 值的比较是什么意思呢?精度何时会完全等于浮点数可以容纳的最大值?

4

2 回答 2

2

如果您按照他对整个源文件的链接进行操作,那么这一点会更有意义。这是一个稍大的片段:

Location bestResult = null;
float bestAccuracy = Float.MAX_VALUE;
long bestTime = Long.MIN_VALUE;

// Iterate through all the providers on the system, keeping
// note of the most accurate result within the acceptable time limit.
// If no result is found within maxTime, return the newest Location.
List<String> matchingProviders = locationManager.getAllProviders();
for (String provider: matchingProviders) {
  Location location = locationManager.getLastKnownLocation(provider);
  if (location != null) {
    float accuracy = location.getAccuracy();
    long time = location.getTime();

    if ((time > minTime && accuracy < bestAccuracy)) {
      bestResult = location;
      bestAccuracy = accuracy;
      bestTime = time;
    }
    else if (time < minTime && bestAccuracy == Float.MAX_VALUE && time > bestTime) {
      bestResult = location;
      bestTime = time;
    }
  }
}

很简单,Float.MAX_VALUE是他的默认值bestAccuracy,他只是检查他没有在前面的if子句中减少它。

于 2011-07-01T17:21:23.000 回答
2

I'm guessing that bestAccuracy has been initialized to Float.MAX_VALUE. If so it looks like the code can be summarized as: find the provider with the smallest (best?) accuracy with time greater than minTime. If there is no time greater than minTime, then just take the one with the time closest to minTime.

This could be refactored from

    if ((time < minTime && accuracy < bestAccuracy)) {
      bestResult = location;
      bestAccuracy = accuracy;
      bestTime = time;
    }
    else if (time > minTime && bestAccuracy == Float.MAX_VALUE && time < bestTime) {
      bestResult = location;
      bestTime = time;
    }

to

    if ((time < minTime && accuracy < bestAccuracy)) {
      bestResult = location;
      bestAccuracy = accuracy;
      bestTime = time;
      foundWithinTimeLimit = true;
    }
    else if (time > minTime && !foundWithinTimeLimit && time < bestTime) {
      bestResult = location;
      bestTime = time;
    }

makes it a little bit clearer.

于 2011-07-01T17:23:47.543 回答