所以我遇到了以下问题: 我们有一只兔子站在一条线上,编号为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);
}
未执行。我似乎无法找到我的错误。任何人?
答案 0 :(得分:1)
在你的递归方法中,你并没有总计来自行中其他兔子的返回值。此外,您只需要一个参数 - 正在考虑哪个兔子。
/*
* 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约定。
答案 1 :(得分:-1)
试试这段代码
import java.util.Scanner;
public class BunnyEars {
static int e=0;
public static int CountEars(int i) {
if (i == 0) {
return e;
} else if (i > 0) {
if (i % 2 == 0) {
e = e + 2;
//i = i - 1;
CountEars(i-1);
} else {
e = e + 3;
//i = i - 1;
CountEars(i-1);
}
}
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);
System.out.println("Number of ears are: " + result);
}
}