查找数组中int数的最小值(Java) [英] Finding the minimum value of int numbers in an array (Java)

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

问题描述

我正在尝试在数组中查找数字的最小值,但并非总是能正常工作.这是我写的代码:

I'm trying to find the minimum value of numbers in an array but it doesn't always work out properly. This is the code I wrote:

        for (int i=0; i < arr.length; i++ ) {
        min = arr[i];
        for (j=0; j < arr.length; j++) {
        if (arr[j] < arr[0]) {
            min = arr[j];
         }
        }
    }   

有人可以纠正我吗?

推荐答案

不需要外部循环,它只运行一次,而且您也不会使用i.你为什么有它?

There's no need for the outer loop, it only runs once and you don't use i anyway. why do you have it?

对于内部循环,您需要与最小值进行比较.现在,您正在将其与数组中的第一个元素(不一定是最小值)进行比较.

For the inner loop, you need to compare against the minimum value. Right now you are comparing it against the first element in the array, which is not necessarily the minimum value.

min = arr[0];
for (j=0; j < arr.length; j++) {
    if (arr[j] < min) {  //<---fix is here
        min = arr[j];
    }
}

您还可以从1开始循环,因为您不需要将arr[0]与自身进行比较(它只是分配给min)

Also you could start the loop at 1, since you don't need to compare arr[0] against itself (it was just assigned to min)

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

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