gpt4 book ai didi

Java,查找数组中的最小数字

转载 作者:行者123 更新时间:2023-11-29 09:39:43 25 4
gpt4 key购买 nike

这是过去一篇论文中的一个问题。我被要求创建一个静态方法 arrayMin 来查找数组 arr 中的最小值。

我必须使用 while 循环,在每次迭代中,变量 min 将返回第一个 i 元素中的最小数字。

有没有办法在不调用另一个方法/for 循环并严格使用 while 循环的情况下做到这一点,因为这个问题只值 4%(包括编写循环不变量和 javadoc)。不确定我是否使问题过于复杂。

public class Revision {

public static int arr[] = new int[] { 5, 8, 4, 3, 6, 2 };
public static int min = 1;

public static int arrayMin() {

int i = 0;

if (arr == null) {
return 0;

} else {
while (i < arr.length) {
// some function/method call to find smallest number of arr[i]
i++;
return min;
}
}
return min;
}

public static void main(String[] args) {

System.out.println(arrayMin());
}

}

最佳答案

一些事情:

  1. 数组不应该是静态的,你应该将它作为一个参数传递给arrayMin方法;
  2. min应该是本地arrayMin可变的,不是静态的;
  3. min应初始化为 Integer.MAX_VALUE .如果你用 1 初始化它, 和 2恰好是数组的最小值,你永远不会返回它;
  4. 您不能从一个方法返回多次。只要你做return min ,方法结束。对于变量 min 将返回前 i 个元素中的最小数字 短语可能存在一些混淆。这可能意味着在每次迭代中,变量min拥有(不返回)第一个 i 中的最小数字元素。

这是一个重构:

public static int arrayMin(int[] arr) {
int i = 0;
int min = Integer.MAX_VALUE;
if (arr == null) {
return 0; // What if 0 is the minimum value? What do you want to do in this case?
} else {
while (i < arr.length) {
if (arr[i] < min) {
min = arr[i];
}
i++;
}
}
return min;
}

关于Java,查找数组中的最小数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12122232/

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