古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?

来源:互联网 发布:视频音频合并软件 编辑:程序博客网 时间:2024/05/01 19:43

题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少? 


import java.util.Scanner; 
public class Rabbit{
public static void main(String[] args){
//int s1=1,s2=1,sum;
Scanner input = new Scanner(System.in);
System.out.print("请输入要查询的月份:");
int mouth=input.nextInt();
/*for(int i=1;i<mouth;i++){           
if(mouth==1||mouth==2){
break;
}else{
sum=s1+s2;
s2=s1;
s1=sum;
}
}
System.out.println("第"+mouth+"个月共有"+sum+"个兔子");*/
/*for(int i=1;i<(mouth%2==0?mouth/2:(mouth/2+1));i++){        //迭代 

}
s1=s1+s2;     //下一个月
s2=s1+s2; //下两个月
}
System.out.println("第"+mouth+"个月共有"+(mouth%2==0?s2:s1)+"个兔子");*/

System.out.println("第"+mouth+"个月共有"+f(mouth)+"个兔子");
}
public static int f(int mouth){           //递归
if(mouth==1||mouth==2){
return 1;
}else{
return f(mouth-1)+f(mouth-2);
}
}
}

阅读全文
0 0
原创粉丝点击