在阅读Android developers blog post on 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;
}
}
}
虽然其余部分非常明确,但这条线让我感到难过:
else if (time < minTime &&
bestAccuracy == Float.MAX_VALUE && time > bestTime){
'时间'必须在可接受的延迟期内&amp;比之前的bestTime更新。那讲得通。
但bestAccuracy与Max Float值的比较是什么意思?什么时候精度可以精确地等于浮点数可以容纳的最大值?
答案 0 :(得分: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
子句中没有减少它。
答案 1 :(得分:2)
我猜测bestAccuracy
已初始化为Float.MAX_VALUE。如果是这样,代码可以概括为:找到具有最小(最佳?)精度且时间大于minTime的提供者。如果没有时间大于minTime,那么只需选择时间最接近minTime的那个。
这可以从
重构 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;
}
到
if ((time < minTime && accuracy < bestAccuracy)) {
bestResult = location;
bestAccuracy = accuracy;
bestTime = time;
foundWithinTimeLimit = true;
}
else if (time > minTime && !foundWithinTimeLimit && time < bestTime) {
bestResult = location;
bestTime = time;
}
让它更清晰一点。