所以我遇到了以下问题: 我们有几只兔子站成一排,编号为 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/