找到最大和最小数的指数在2D阵列小数、阵列、大和、指数

2023-09-11 07:00:10 作者:南城以南溫暖如初

我真的难倒试图找到一个5x5的阵列的最大和最小的数字随机数高达1000产生到他们的指数。在这里,我的code:

 导入了java.util.Random;

公共类MaxMinArray {

    公共静态无效的主要(字符串的args []){

    INT X = 0,Y = 0,最大= 0,最小= 1000 ;;
    INT [] []号码=新INT [5] [5];

    为(X = 0; X  - 其中; numbers.length; X ++){//用于外
        对于(Y = 0; Y< numbers.length; Y ++){//内的
            号码[X] [Y] =(INT)(的Math.random()* 1000); //随机数发生器

            如果(MAX<数字[X] [Y])//最大数量
                最大=数字[X] [Y]

            如果(分>数字[X] [Y])//分钟数
                分=数字[X] [Y]

            INT maxIndex = 0;

            对于(INT指数= 1;指数< numbers.length;指数++)
                如果(编号[maxIndex]<数字[指数])
                    maxIndex =指数;
            }
        }
        的System.out.println(数组中的最大数:+ MAX +);
        的System.out.println(最大数目是+ maxIndex +);
        的System.out.println(数组中最小数:+分钟+);
    }
}
 

解决方案

您应该跟踪的两个 X 最大/最小元素的索引。无需后期处理,这簿记只是一个问题:

 如果(MAX<数字[X] [Y]){
    最大=数字[X] [Y]
    MAXX = X;
    MAXY = Y;
}
 
求解一道VB程序设计题 定义一个二维数组a,共4行4列 要求 1 用随机函数产生 范围内的随机整数,并赋值给数组元素,并把改数组以4行4列的形式显示在窗体上

I'm really stumped trying to find the index of the largest and smallest numbers of a 5x5 array with random numbers up to 1000 generated into them. Here my code:

import java.util.Random;

public class MaxMinArray {

    public static void main (String args[]) {

    int x=0, y=0, max=0, min=1000;;
    int[][] numbers = new int[5][5];

    for (x=0; x<numbers.length; x++) {                  //outer for          
        for(y=0; y<numbers.length; y++) {               //inner for    
            numbers[x][y]= (int)(Math.random()*1000);   //random generator

            if(max < numbers[x][y])                     //max number
                max = numbers[x][y];

            if(min>numbers[x][y])                       //min number
                min = numbers[x][y];

            int maxIndex = 0;

            for(int index = 1; index<numbers.length; index++)
                if(numbers[maxIndex]< numbers[index])
                    maxIndex = index;
            }
        }
        System.out.println("Max number in array:" + max + " ");
        System.out.println("Max number is in" + maxIndex + " ");
        System.out.println("Min number in array:" + min + " ");
    }
}

解决方案

You should keep track of both the x and y index of the maximum/minimum element. No need to post-process, it's just a matter of bookkeeping:

if(max < numbers[x][y]) {
    max = numbers[x][y];
    maxX = x;
    maxY = y;
}