简体   繁体   English

通过for循环获取最小值及其索引

[英]Get the minimum value and its index with a for loop

How can I get the minimum value in a for loop plus its index:? 如何获得for循环中的最小值及其索引:?

Update: This is what I tried after using @Sakalya 's answer 更新:这是我在使用@Sakalya的答案后尝试过的方法

      LatLng myLatLang = new LatLng(myLocation.getLatitude(),myLocation.getLongitude());

        double minval = -1.0;
        int minIndex = 0;

        for (int i = 0; i < stationsCoord.size(); i++) {

            double distance = CalculationByDistance(myLatLang,stationsCoord.get(i));

            if(distance < minval){
                minval = distance;
                minIndex = i;
            }

            Log.i("distance " , String.valueOf(distance));

            System.out.println("min=" +minval+ "index="+minIndex);

        }

      //i'm looking for the min value of 'distance' + the index 'i'

I always get this: System.out: min=-1.0index=0 我总是这样: System.out: min=-1.0index=0

Thank you in advance. 先感谢您。

First you can set a min variable to 1000000 and then iterate the list to find min value as below: 首先,您可以将min变量设置为1000000,然后迭代列表以找到min值,如下所示:

LatLng myLatLang = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());

double minval = 1000000000000.0;
int minIndex = 0;

for (int i = 0; i < stationsCoord.size(); i++) {

    double distance = CalculationByDistance(myLatLang,stationsCoord.get(i));

    if (distance < minval) {
      minval = distance;
      minIndex = i;
    }

    Log.i("distance " , String.valueOf(distance));

    System.out.println("min=" +minval+ "index="+minIndex);

}

In the following code 在下面的代码中

double minval = -1.0;
if (somepositivedistance < minval ) { // do something
}

nothing will ever return true if the distance is positive, therefore the statement will never execute. 如果距离为正,则不会有任何结果返回true,因此该语句将永远不会执行。

You need to set minval to something greater then the largest possible distance (for example Double.MAX_VALUE ) before entering the for-loop. 在进入for循环之前,您需要将minval设置为大于最大可能距离的值(例如Double.MAX_VALUE )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM