Finding the index number of the lowest value in an array

后端 未结 4 812
借酒劲吻你
借酒劲吻你 2021-01-21 22:32

I have to return the index number of the lowest value in an array of 12 numbers. I keep getting 12 as the result every time I run it. Here is my code:

minRain =          


        
相关标签:
4条回答
  • 2021-01-21 22:53

    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;  
    }
    
    0 讨论(0)
  • 2021-01-21 22:55

    You are assigning array value to the lowest, so change it as shown below:

    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;  
    }
    
    0 讨论(0)
  • 2021-01-21 22:56

    You need to store lowest_seen and lowest_index. Right now you are comparing value < last_index

    0 讨论(0)
  • 2021-01-21 23:12

    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;
    
    0 讨论(0)
提交回复
热议问题