二维阵列中最大值和最小值的差异[重复]

时间:2021-06-24 22:54:22

This question already has an answer here:

这个问题在这里已有答案:

Below is my program that attempts to find the absolute value of the difference between the max and minimum values inside a two-dimensional array. Unfortunately, I keep on receiving 1 as the answer, when it should be 12 (Math.abs(7-(-5)). My guess is that there is a simple error in the code that I am missing out on.

下面是我的程序,它试图找到二维数组内最大值和最小值之差的绝对值。不幸的是,我继续收到1作为答案,当它应该是12(Math.abs(7 - ( - 5))。我的猜测是,我错过的代码中有一个简单的错误。

class Main
{
public static void main(String[] args)
{
    int[][] a = {
        {-5,-2,-3,7},
        {1,-5,-2,2},
        {1,-2,3,-4}
    };
    System.out.println(diffHiLo(a)); //should print 12
}

public static int diffHiLo(int[][] array)
{
    int max = Integer.MAX_VALUE;
    int min = Integer.MIN_VALUE;

    for (int[] cool : array){
      for(int z: cool){
        if (z < min )
          min = z;
        else if (z > max)
          max = z;
      }
    }

    return Math.abs(max-min);    
  }
}

1 个解决方案

#1


2  

You should initialize min to Integer.MAX_VALUE and max to Integer.MIN_VALUE. You are doing the opposite, causing your loop to do nothing (since z is never smaller than min or larger than max).

您应该将min初始化为Integer.MAX_VALUE,并将max初始化为Integer.MIN_VALUE。你正在做相反的事情,导致你的循环什么都不做(因为z永远不会小于min或大于max)。

The result you get is 1 because min and max are not changed by your loop and Integer.MAX_VALUE-Integer.MIN_VALUE is -1 (due to numeric overflow).

得到的结果是1,因为循环不会更改min和max,并且Integer.MAX_VALUE-Integer.MIN_VALUE为-1(由于数字溢出)。

#1


2  

You should initialize min to Integer.MAX_VALUE and max to Integer.MIN_VALUE. You are doing the opposite, causing your loop to do nothing (since z is never smaller than min or larger than max).

您应该将min初始化为Integer.MAX_VALUE,并将max初始化为Integer.MIN_VALUE。你正在做相反的事情,导致你的循环什么都不做(因为z永远不会小于min或大于max)。

The result you get is 1 because min and max are not changed by your loop and Integer.MAX_VALUE-Integer.MIN_VALUE is -1 (due to numeric overflow).

得到的结果是1,因为循环不会更改min和max,并且Integer.MAX_VALUE-Integer.MIN_VALUE为-1(由于数字溢出)。