【问题标题】:Difference of Max and Min in a 2-D Array [duplicate]二维数组中最大值和最小值的差异
【发布时间】:2017-09-28 12:51:14
【问题描述】:

下面是我的程序,它试图找到二维数组中最大值和最小值之差的绝对值。不幸的是,我一直收到 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);    
  }
}

【问题讨论】:

  • 您反向初始化 maxmin。设置max = Integer.MIN_VALUEmin = Integer.MAX_VALUE;

标签: java max min absolute


【解决方案1】:

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

您得到的结果是1,因为minmax 不会被您的循环更改,而Integer.MAX_VALUE-Integer.MIN_VALUE-1(由于数字溢出)。

【讨论】:

    猜你喜欢
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 2019-03-31
    • 2015-04-06
    • 2014-12-27
    • 2011-05-28
    相关资源
    最近更新 更多