所以我遇到了下面的问题:我们有兔子排成一列,编号为1,2,...奇数兔(1,3,..)偶数兔(2,4,..)我们说有3只耳朵,因为它们每只都有一只抬起的脚。递归返回bunny行1,2,...中的"ears“数
这是我的源代码。我使用的是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。
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);
} 没有执行。我似乎找不到我的错误。有没有人?
发布于 2015-05-25 00:40:15
在您的递归方法中,您不会合计来自行中其他bunnies的返回值。而且,您只需要一个参数--正在考虑的是哪只兔子。
/*
* 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约定。
发布于 2015-05-24 20:33:07
试试这段代码
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);
}
}https://stackoverflow.com/questions/30423460
复制相似问题