简体   繁体   English

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

[英]Finding the index number of the lowest value in an array

I have to return the index number of the lowest value in an array of 12 numbers. 我必须返回12个数字数组中最低值的索引号。 I keep getting 12 as the result every time I run it. 每次运行时我都会得到12分。 Here is my code: 这是我的代码:

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));

What is the meaning of this statement? 这个陈述的含义是什么?

int lowest = (int) mon4[0];

You are saving the first value of the array as the lowest one and then later comparing with array values. 您将数组的第一个值保存为最低值,然后与数组值进行比较。 You are actually comparing index with array values. 您实际上是将索引与数组值进行比较。

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

You should do something like this. 你应该做这样的事情。

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

It is a silly mistake you made - you assigned index to your variable instead of an array value. 这是一个愚蠢的错误 - 您为变量指定了索引而不是数组值。 Do this: 做这个:

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;  
}

You are assigning array value to the lowest , so change it as shown below: 您将数组值分配给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;  
}

You need to store lowest_seen and lowest_index. 您需要存储lowest_seen和lowest_index。 Right now you are comparing value < last_index 现在你正在比较值<last_index

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

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