使用for循环在数组中查找最大值和最小值?

试图在 java 中找到随机生成的数组的最小值/最大值。我的代码正在寻找最大值,但是我不确定为什么当我尝试运行它时,最小值每次都会出现 0.0。


public static void main(String[] args) {

    double array1[] = new double [10];

    int n = array1.length;

    double max = array1[0];

    double min = array1[1];


    System.out.println("Array: ");


    for (int i=0; i<n; i++) {

        array1[i] = Math.floor((Math.random() * 100) + 1);

        System.out.print(array1[i]+ " | " );

        if (array1[i] > max) {

             max = array1[i];

        } 

        if (min > array1[i]) {

             min = array1[i];



            }


        }


 }


呼如林
浏览 331回答 4
4回答

慕标琳琳

据我所知,最小值为 0.0 的原因是因为它是空数组中元素的默认值,所以当您尝试在整个随机生成的数组中比较最小值仅为 1 时,内部的值min 变量永远不会被更新。尽管数组中的元素尚未初始化,但您已经将 min 指定为数组的第二个元素。尝试在比较循环之前处理的不同循环中初始化数组,或者将 min 变量分配为随机生成器的最大值,然后它可能会顺利运行。for(int i= 0;i<n;i++)&nbsp; &nbsp;array1[i] = Math.floor((Math.random() * 100) + 1);max = array[0];min = array[0];for(int i = 1;i<n;i++){&nbsp; System.out.print(array1[i]+ " | " );&nbsp; //continue ...}或这个min = 100;max = 1;for(int i = 0; i<n;i++){&nbsp; &nbsp;//continue ...}

HUX布斯

一种相当标准的方法是使用“最坏情况”值初始化最小/最大变量:double&nbsp;max&nbsp;=&nbsp;Double.MIN_VALUE; double&nbsp;min&nbsp;=&nbsp;Double.MAX_VALUE;这也将解决您的问题,因为您不会生成任何低至 的值0.0,这是您访问数组以将值分配给minand时所保存的值max。此外,在您的循环中,您可以简化为:max&nbsp;=&nbsp;Math.max(max,&nbsp;array[i]); min&nbsp;=&nbsp;Math.min(min,&nbsp;array[i]);

阿晨1998

&nbsp; &nbsp; // using forloop// max number in arrry&nbsp; &nbsp; const arr = [2, 3, 5, 10, 8, 3];&nbsp; &nbsp; let max = 0;&nbsp; &nbsp; for (i = 0; i < arr.length; i++) {&nbsp; &nbsp; &nbsp; if (arr[i] > max) {&nbsp; &nbsp; &nbsp; &nbsp; max = arr[i];&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; console.log(max);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // max number in arrry&nbsp; &nbsp; let min = 100;&nbsp; &nbsp; for (i = 0; i < arr.length; i++) {&nbsp; &nbsp; &nbsp; if (arr[i] < min) {&nbsp; &nbsp; &nbsp; &nbsp; min = arr[i];&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; console.log(min);

GCT1015

//find maximum&nbsp; and min number in array using funtionconst maxArrayNum = (arr) => {&nbsp; let max = Math.max(...arr);&nbsp; return max;};const minArrayNum = (arr) => {&nbsp; let min = Math.min(...arr);&nbsp; return min;};const maxNum = maxArrayNum([3, 4, 2, 1]);console.log(maxNum);const minNum = minArrayNum([3, 4, 2, 1]);console.log(minNum);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java