gpt4 book ai didi

java - 递归查找数组中的最大数

转载 作者:行者123 更新时间:2023-12-02 06:19:12 26 4
gpt4 key购买 nike

我试图通过一些代码来理解递归。这段代码应该递归地找到数组中的最大数字,但由于某种原因它不起作用。感谢您的帮助!

public static void main(String[] args) {
int array [] = {11,4,6,9,15,2};

maxNum(array, 1, 0);

}//Main

public static int maxNum(int array[], int maxIndex, int i)
{
int ans;

if(i==array.length-1) //Condition Stop
{
ans= maxIndex;
}
else
{
ans= maxNum(array, Math.max(array[maxIndex], array[i]), i++);
}
System.out.println(array[maxIndex]);
return ans;

}//maxNum
}//Class

最佳答案

我发现位 Math.max(array[maxIndex], array[i]) 有问题。您将其用作递归调用 maxNum() 的第二个参数。 ,但您从数组中获取,而不是索引。换句话说,您最终将使用数组中的某个值(例如 11 或 15)作为索引。

关于java - 递归查找数组中的最大数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21163204/

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