gpt4 book ai didi

java - 数组怪癖中的最小数字

转载 作者:搜寻专家 更新时间:2023-11-01 04:02:41 25 4
gpt4 key购买 nike

我正在尝试解决 CodeWars 上的一个问题,该问题让我找到数组中的最小数字。这是我当前的代码:

public class SmallestIntegerFinder {
public int findSmallestInt(int[] args){
int smallest = args[0];
for(int i=1; i < args.length; ++i){
if(args[i] < args[0]){
smallest = args[i];
}
}
return smallest;
}
}

为什么这行不通?但是,当我将 if 语句中的 args[0] 更改为变量 smallest 时,它起作用了。两者有什么区别?它们都指向 args[0],不是吗?

public class SmallestIntegerFinder {
public int findSmallestInt(int[] args){
int smallest = args[0];
for(int i=1; i < args.length; ++i){
if(args[i] < smallest){
smallest = args[i];
}
}
return smallest;
}
}

我使用的测试数组是:{78,56,232,12,11,43}

最佳答案

因为 args[0] 是数组中的第一个元素,而 smallest 从第一个元素开始;它更新为下一个最小值(考虑 3、1、2;2 小于 3 但 1 小于 2)。您也可以使用 Math.min(int, int)喜欢

public int findSmallestInt(int[] args) {
int smallest = args[0];
for (int i = 1; i < args.length; ++i) {
smallest = Math.min(smallest, args[i]);
}
return smallest;
}

关于java - 数组怪癖中的最小数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36411941/

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