This question already has answers here:
Java - Finding/Printing Min/Max with Array?
(3个答案)
2年前关闭。
下面是我的程序,试图找到二维数组内最大值和最小值之差的绝对值。不幸的是,当数值应该为12时,我一直收到1作为答案(Math.abs(7-(-5))。
(3个答案)
2年前关闭。
下面是我的程序,试图找到二维数组内最大值和最小值之差的绝对值。不幸的是,当数值应该为12时,我一直收到1作为答案(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);
}
}
最佳答案
您应该将min
初始化为Integer.MAX_VALUE
,将max
初始化为Integer.MIN_VALUE
。您做相反的事情,导致循环不执行任何操作(因为z
永远不会小于min
或大于max
)。
您得到的结果是1
,因为循环不会更改min
和max
,并且Integer.MAX_VALUE-Integer.MIN_VALUE
是-1
(由于数字溢出)。
关于java - 二维数组中的最大值和最小值之差,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43713464/