兔子问题是典型的斐波那契数列的问题,我们采用递归的方式来做
import java.util.Scanner;
public class Rabbit {
public static void main(String[] args) {
System.out.println("输入月份:");
Scanner a = new Scanner(System.in);
int getMonth = a.nextInt();
System.out.println("第"+getMonth+"月的兔子有:"+getNum(getMonth)+"只");
}
//采用递归的方式,减少代码量
private static int getNum(int getMonth){
if (getMonth == 1 || getMonth == 2)
return 1;
else {
return getNum(getMonth-1) + getNum(getMonth - 2);
}
}
}