1.有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,请编程输出两年内每个月的兔子总数为多少?

<?php
   function getResult($month){
      $one = 1; //第一个月兔子的对数
      $two = 1; //第二个月兔子的对数
      $sum = 0; //第$month个月兔子的对数
      if($month < 3){
         return ;
         }
      for($i = 2;$i < $month; $i++){
         $sum = $one + $two;
         $one = $two;
         $two = $sum;
      }
      echo $month.'个月后共有'.$sum.'对兔子';
   }

第二种方法(递归):

<?php 
   function fun($n){
   if($n == 1 || $n == 2){
       return 1;
   }else{
       return fun($n-1)+fun($n-2);
   } 
}

相关文章:

  • 2022-01-07
  • 2021-06-04
  • 2022-12-23
  • 2021-07-18
  • 2022-03-09
  • 2022-02-19
  • 2021-11-30
  • 2021-05-09
猜你喜欢
  • 2022-12-23
  • 2021-08-01
  • 2022-12-23
  • 2021-05-12
  • 2021-05-18
  • 2021-07-25
  • 2021-12-28
相关资源
相似解决方案