public class RecursionExercise{
public static void main(String[] args){
T t = new T();
//斐波那契数
int n = 7;
int res = t.Fibonacci(n);
if(res != -1){
System.out.println("当n为"+ n +"时,它的斐波那契数为res = " + res);
}
System.out.println("========");
//猴子吃桃问题
int day = 1;
int peachNum = t.peach(day);
if(peachNum != -1){
System.out.println("第"+ day +"天一共有peachNum = " + peachNum + "个桃子");
}else{
System.out.println("请输入1-10天之间");
}
}
}
class T{
public int Fibonacci(int n){
//使用递归方法求出斐波那契数,1, 1, 2, 3, 5, 8, 13, ...求整数n的值
if(n >= 1){
if(n > 2){
// System.out.println("当n为"+ n +"时,f =" + Fibonacci(n - 2) + Fibonacci(n - 1));
return (Fibonacci(n - 2) + Fibonacci(n - 1));
}else{
// Fibonacci(n) = 1;
// System.out.println("当n为"+ n +"时,f =" + Fibonacci(n));
return 1;
}
}else{
System.out.println("请输入大于等于1的数");
}
return -1;
}
public int peach(int n){
//猴子吃桃问题
if(n >= 1 && n < 10){
return (peach(n + 1) + 1) * 2;//规律:前一天的桃子 = (后一天的桃子 + 1) * 2
}else if(n == 10){
return 1;
}else{
System.out.println("请输入1-10天");
}
return -1;
}
}