猿问

为什么这个函数总是返回 0 或 1

我正在尝试学习一些关于递归的知识,所以我正在尝试做一些练习,但现在我有点卡住了,因为我不知道为什么这个函数总是返回 1 或 0 我试图计算数量11 在 int 数组中的出现。


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));

    }

}


有只小跳蛙
浏览 99回答 3
3回答

湖上湖

它返回0一个空数组和1一个非空数组。您看到的结果来自index,而不是count您期望的结果。我会在不涉及领域的情况下编写它。public int m(int[] nums, int index, int count) {&nbsp; &nbsp; return index < nums.length ?&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m(nums, index + 1, nums[index] == 11 ? ++count : count) :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count;}或(@Pshemo 在评论中建议)public int m(int[] nums, int index) {&nbsp; &nbsp; return index < nums.length ?&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (nums[index] == 11 ? 1 : 0) + m(nums, ++index) :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 0;}

扬帆大鱼

您返回索引。标记您的问题:public class Uloha06 {&nbsp; &nbsp; public static int count = 0;&nbsp; &nbsp; public static int array11(int[] nums, int index){&nbsp; &nbsp; &nbsp; &nbsp; if(index<nums.length){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(nums[index]==11)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;count+=1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;index++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;array11(nums,index);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;/// booom here index is 1 but you want count&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//if(index<nums.length)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//&nbsp; &nbsp; return index;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return count;&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; // TODO Auto-generated method stub&nbsp; &nbsp; &nbsp; &nbsp; int array11[]={11,1,2,36,11};&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(array11(array11, 0));&nbsp; &nbsp; &nbsp;}

30秒到达战场

这应该工作public static int array11(int[] nums, int index){if(index < 0){&nbsp; &nbsp; return 0;}&nbsp;else if (nums [index] == 11)&nbsp;{&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; return (array11(nums, index-1) + 1);&nbsp;}&nbsp; &nbsp;else {&nbsp; &nbsp; &nbsp; return&nbsp; array11(nums, index-1);&nbsp; &nbsp;}}&nbsp;
随时随地看视频慕课网APP

相关分类

Java
我要回答