【发布时间】: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);
}
}
【问题讨论】:
-
您反向初始化
max和min。设置max = Integer.MIN_VALUE和min = Integer.MAX_VALUE;