查找数组中最低值的索引号

时间:2017-05-05 20:58:45

标签: java arrays

我必须返回12个数字数组中最低值的索引号。每次运行时我都会得到12分。这是我的代码:

minRain = leastRain(months);

public static int leastRain (double[] mon4){
    int lowest = (int) mon4[0];

    for (int index=1; index<mon4.length; index++){
        if (mon4[index]<lowest)
            lowest = index;
    }
    return lowest;  
}

System.out.println("The month with the lowest amount of rain is: " + (minRain + 1));

4 个答案:

答案 0 :(得分:3)

这个陈述的含义是什么?

int lowest = (int) mon4[0];

您将数组的第一个值保存为最低值,然后与数组值进行比较。您实际上是将索引与数组值进行比较。

if (mon4[index]<lowest) // comparing lowest as an array value
    lowest = index;     // saving the index as the lowest value

你应该这样做。

 if (mon4[index]<mon4[lowest]) // comparing value of 'index' 'vs. 'lowest' index location
     lowest = index;

答案 1 :(得分:2)

这是一个愚蠢的错误 - 您为变量指定了索引而不是数组值。这样做:

public static int leastRain (double[] mon4){
    int lowest = 0;

    for (int index=1; index<mon4.length; index++){
        if (mon4[index]<mon4[lowest])
            lowest = index;
    }
    return lowest;  
}

答案 2 :(得分:2)

您正在为lowest分配数组值,因此请按如下所示进行更改:

public static int leastRain (double[] mon4){
    int lowestIndex = 0;//set index as 0 instead of array value
    int lowestValue = mon4[0];
    for (int index=1; index<mon4.length; index++){
        if (mon4[index] < lowestValue)
            lowestIndex = index;
    }
    return lowestIndex;  
}

答案 3 :(得分:0)

您需要存储lowest_seen和lowest_index。现在你正在比较价值&lt; last_index