【发布时间】:2019-06-26 19:48:44
【问题描述】:
我正在尝试学习一些关于递归的知识,所以我正在尝试做一些练习,但现在我有点卡住了,因为我不明白为什么这个函数总是返回 1 或 0 我正在尝试计算 int 数组中 11 的出现次数。
public class Uloha06 {
public static int count = 0;
public static int array11(int[] nums, int index){
if(index<nums.length){
if(nums[index]==11)
count+=1;
index++;
array11(nums,index);
if(index<nums.length)
return index;
}
return count;
}
public static void main(String[] args) {
int array11[]={11,1,2,36,11};
System.out.println(array11(array11, 0));
}
}
【问题讨论】:
-
看起来你没有对递归调用的结果做任何事情
array11(nums,index);- 如果返回计数为 1,它会发生什么?您应该将其添加到 count 变量中吗? -
Java 使用传值方式,所以
count最多更新一次。 -
if(index<nums.length) return index;的目的是什么? -
@Pshemo 哇,你刚刚解决了我的问题,返回计数就足够了。似乎很清楚我应该返回索引:D 现在当我看到它时,我觉得真的很愚蠢:D thx man
-
顺便说一句,您应该避免在递归中使用字段(例如
counter)。例如,您可以使用我们可以使用的相同技术来编写递归求和,它可能看起来像return currentElement + recursiceSumOfPreviousElements。在这里,您的currentElement将是 1 或 0,具体取决于当前索引处的值是否为 11。所以你的递归看起来像public static int count11(int[] nums, int index){ if (index < nums.length) return (nums[index] == 11 ? 1 : 0) + count11(nums, index + 1); else return 0; }