gpt4 book ai didi

java - 二维数组中最大值和最小值的差异

转载 作者:行者123 更新时间:2023-11-30 02:33:28 25 4
gpt4 key购买 nike

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

最佳答案

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

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

关于java - 二维数组中最大值和最小值的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43713464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com