java - 递归练习

标签 java recursion

所以我遇到了以下问题: 我们有几只兔子站成一排,编号为 1, 2, ... 奇数兔子 (1, 3, ..) 有正常的 2 个耳朵。偶数兔子(2、4、..)我们会说它们有 3 个耳朵,因为它们每个都有一只抬起的脚。递归返回兔子第 1, 2, ... n 行中“耳朵”的数量(没有循环或乘法)。

这是我的源代码。我正在使用 Java

import java.util.Scanner;

public class BunnyEars
{
    public static int CountEars(int i, int e)
    {
        if(i == 0)
        {
            return e;
        }
        else if(i > 0)
        {
            if(i%2==0)
            {
                e = e + 2;
                i = i - 1;
                CountEars(i,e);
            }
            else
            {
                e = e + 3;
                i = i - 1;
                CountEars(i,e);
            }       
        }
        return e;
    }

public static void main(String []args)
{
    Scanner scan = new Scanner(System.in);

    int b;
    int result;

    System.out.println("Bunny Ears, even has 2 ears, odd has 3 ears");
    System.out.println("Please enter a value: ");
    b = scan.nextInt();

    result = CountEars(b,0);

    System.out.println("Number of ears are: " + result);
}

如果我输入 5,输出应该是 12,但输出是 3。 所以我认为

中的 CountEars(i,e) 方法
enter code here

if(i%2==0)
        {
            e = e + 2;
            i = i - 1;
            CountEars(i,e);
        }
        else
        {
            e = e + 3;
            i = i - 1;
            CountEars(i,e);
        }   

没有执行。我似乎找不到自己的错误。任何人?

最佳答案

在您的递归方法中,您不会合计行中其他兔子的返回值。另外,您只需要一个参数 - 正在考虑哪只兔子。

/*
 * Return the total number of ears in a line of length n
 */
public static int countEars(int n) {
   if (n < 1) {
      return 0;   // base case: no bunnies, no ears
   }
   // Below we make the "recursive leap of faith": if this
   // function works, we can get the answer for a line of n-1
   // bunnies and add the current bunny's ears to it to yield
   // the correct answer for the current value of n.
   // Note that the argument to the recursive call must
   // converge towards the base case for this to work.
   if (n % 2 == 1) {
      return 2 + countEars(n-1);
   }
   return 3 + countEars(n-1);
}

使用 result = countEars(5); 调用此函数。

请注意,我已重命名您的方法以遵循 Java 约定。

关于java - 递归练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30423460/

相关文章:

java - 在java中一行声明多个对象

java - Flink 1.9.1 无法再连接到 Azure Event Hub

java - 在 GAE Java 上将文件上传到 Google 存储

haskell - QuickCheck 放弃研究递归数据结构(玫瑰树)。

recursion - "foop": a naming convention? 它 's a helper recursive function for "foo "; what does the suffix "p“是什么意思?

java - 在不同平台上从 Java 代码运行 adb shell 命令

java - 在新窗口中自动提交表单

algorithm - 如何找到二维数组中最长的序列?

java - 关于 Java 新手的递归

algorithm - 为什么递归归并排序优于迭代归并排序,即使后者具有辅助空间复杂性?