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

  1. /*

  2. 2017年2月15日13:32:10

  3. java基础50道经典练习题 例1

  4. Author: ZJY

  5. Purpose: 菲波拉契数列应用

  6. 【程序1】

  7. 题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,

  8. 小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,

  9. 问每个月的兔子对数为多少?

  10. 程序分析: 兔子的规律为数列1,1,2,3,5,8,13,21....

  11.  
  12. */

  13. import java.util.Scanner;

  14.  
  15. public class ProgramNO1

  16. {

  17.  
  18. /* 方法一: 递归

  19. public static void main(String[] args) {

  20. int n = 5;

  21.  
  22. System.out.println("第" + n + "个月,兔子的总数为" + fun(n));

  23.  
  24. }

  25. private static int fun(int n) {

  26. if((1 == n)||(2 == n))

  27. return 1;

  28. else

  29. return (fun(n-1) + fun(n-2));

  30. }*/

  31.  
  32. /* 方法二: 循环

  33. public static void main(String[] args) {

  34. int number = 1, month;

  35. int tmp1 = 1, tmp2 = 1;

  36.  
  37. Scanner sc = new Scanner(System.in);

  38. System.out.print("请输入第几个月:");

  39. month = sc.nextInt();

  40.  
  41. for (int i=1; i<=month; i++) {

  42. if(2 >= i)

  43. number = 1;

  44. else {

  45. number = tmp1 + tmp2;

  46.  
  47. tmp2 = tmp1; //第二个月

  48. tmp1 = number; //第一个月

  49. }

  50. }

  51. System.out.println("第" + month + "个月,兔子的总数为:" + number);

  52. }

  53. */

  54. public static void main(String[] args) {

  55. Scanner sc = new Scanner(System.in);

  56. System.out.print("请输入第几个月:");

  57. int month = sc.nextInt();

  58. System.out.println("第" + month + "个月,兔子的总数为:" + fun(month));

  59. }

  60. private static int fun(int month) {

  61. if((1 == month)||(2 == month))

  62. return 1;

  63. else

  64. return (fun(month-1) + fun(month-2));

  65. }

  66. }

  67.  

猜你喜欢

转载自blog.csdn.net/zxfly6/article/details/81408603