查找数组中最小值的索引号 [英] Finding the index number of the lowest value in an array

查看:77
本文介绍了查找数组中最小值的索引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须返回12个数字组成的数组中最小值的索引号.每次运行时,结果始终保持12.这是我的代码:

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

推荐答案

您正在将数组值分配给最低,因此如下所示进行更改:

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

这篇关于查找数组中最小值的索引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆