如何找到2d数组的最大值和最小值的位置

时间:2016-10-04 21:11:32

标签: java arrays loops multidimensional-array max

我不知道我是否清楚这一点,但我已经有了最小和最大的打印权,但我似乎无法弄清楚如何说出确切的行和列他们在... 这就是我到目前为止所拥有的;

double max = m[0][0];
       double min =  m[0][0];
    System.out.println("The matrix is : ");

        for(int i = 0; i < m.length; i++)
        {
            for ( int j = 0; j < m[i].length; j++ )
            {
                System.out.printf("   " + "%6.1f " , m[i][j]);
                if (m[i][j] > max)
                    max = m [i][j];     

                else if
                (m[i][j] < min)
                    min = m [i][j];

我怎样才能说出他们的位置?例如:(&#34;最大数字在第1行,第2列和第34行;)类似的东西...... 我真的很感激任何帮助

2 个答案:

答案 0 :(得分:3)

请参阅以下修改。我添加了变量来跟踪最小值和最大值的索引。在循环结束时,您只需打印出maxIndex1maxIndex2minIndex1minIndex2

double max = m[0][0];
double min =  m[0][0];

//declare variables to track the indices of the min and max
int maxIndex1 = -1;
int maxIndex2 = -1;
int minIndex1 = -1;
int minIndex2 = -1;

System.out.println("The matrix is : ");
for(int i = 0; i < m.length; i++)
{
    for ( int j = 0; j < m[i].length; j++ )
    {
        System.out.printf("   " + "%6.1f " , m[i][j]);
        if (m[i][j] > max)
        {
            max = m [i][j]; 
            //record the indices of the new max
            maxIndex1 = i;
            maxIndex2 = j;  
        }  
        else if (m[i][j] < min)
        {
            min = m [i][j];
            //record the indices of the new min
            minIndex1 = i;
            minIndex2 = j;
        }

请注意,如果您有两个相等且值与数组中的最大值相关联的值,则只会记录其中一个值。如果您想记录最小/最大的所有关系的位置,您可以更改此项以保存坐标列表而不是单个坐标。

答案 1 :(得分:1)

这很容易!只需声明另外两个变量来存储x和y坐标。并在if和else中更新它们(不要忘记在if和else子句中添加花括号!)并且你拥有它们!