java经典问题——生兔子
题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
1.程序分析: 兔子的规律为数列1,1,2,3,5,8,13,21....
从第三个月起,后面的兔子总数都等于前面两个月的兔子总数之和,即为斐波那契数列。
源代码如下:
递归方式:
package rabbit;
import java.util.Scanner;
public class Rabbit {
public static void main(String[] args) {
System.out.println("请输入月份");
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
for (int i = 1; i <= m; i++) {
System.out.println("第" + i + "个月的兔子为:" + f(i));
}
}
public static int f(int x) {
if (x == 1 || x == 2)
return 1;
else
return f(x - 1) + f(x - 2);
}
}
非递归方式:
package rabbit;
import java.util.Scanner;
public class Rabbit1 {
public static void main(String[] args) {
int f1 = 1;
int f2=1;
System.out.println("请输入月份");
Scanner sc=new Scanner(System.in);
int m=sc.nextInt();
int temp = 0;
for (int i = 3; i <=m; i++) {
if (m==1||m==2)
f2=1;
else
temp=f2;
f2=f1+f2;
f1=temp;
}
System.out.println(f2);
}
}
本内容由安康学院"雨季"原创!