Chinaunix首页 | 论坛 | 博客
  • 博客访问: 143925
  • 博文数量: 44
  • 博客积分: 2330
  • 博客等级: 大尉
  • 技术积分: 405
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-09 11:57
文章分类
文章存档

2012年(6)

2011年(32)

2010年(6)

分类: LINUX

2011-04-29 10:56:56

  1. <?php
  2. /*
  3.  * 一头母羊的寿命是5年,它会在第2年底和第4年底各生下一头母羊,第5年底死去,问一开始农场有1头母羊,N年后,农场会有多少只母羊?
  4. 要求:
  5. 用PHP写程序计算。给出两种写法,分别是面向过程的方式和面向对象的方式。
  6. */
  7. class sheep {
  8.     private $_max_age=5;
  9.     private $_curr_age=0;

  10.     function passyear() {
  11.         $this->_curr_age++;
  12.     }

  13.     public function getAge() {
  14.         return $this->_curr_age;
  15.     }
  16. }

  17. /**
  18.  * 羊圈
  19.  */
  20. class house {
  21.     private $_sheep=array();
  22.     private $_curr_year=1;

  23.     function __construct() {
  24.         //初始情况下,放入一只羊

  25.         $this->addSheep();
  26.     }

  27.     function passyear($year)
  28.     {
  29.         for($i=0;$i<$year;$i++)
  30.         {
  31.             $this->passOneYear();
  32.         }
  33.     }

  34.     /**
  35.      * 过一年
  36.      */
  37.     function passOneYear() {
  38.         foreach($this->_sheep as $key=>$value) {
  39.             $value->passyear();
  40.             if($value->getAge()==2) {
  41.                 $this->addSheep();
  42.             }else if($value->getAge()==4) {
  43.                 $this->addSheep();
  44.             }else if($value->getAge()==6) {
  45.                 unset ($this->_sheep[$key]);
  46.             }
  47.         }
  48.         echo $this->_curr_year."==".count($this->_sheep)."
    "
    ;
  49.         $this->_curr_year++;
  50.     }

  51.     /**
  52.      * 加入一只羊
  53.      */
  54.     private function addSheep() {
  55.         $sheep=new sheep();
  56.         array_push($this->_sheep,$sheep);
  57.     }
  58. }

  59. $house=new house();
  60. //过20年

  61. $house->passyear(20);
  62. ?>
  63. <?php
  64. /**
  65.  * 过程
  66.  */
  67. $sheep=array();
  68. //放入一只羊

  69. $one=0;
  70. array_push($sheep, $one);
  71. /**
  72.  * 过N年后
  73.  */
  74. $N=20;
  75. for($i=1;$i<=$N;$i++)
  76. {
  77.     foreach($sheep as $key=>$value)
  78.     {
  79.         $sheep[$key]++;
  80.         if($value==1 || $value==3)
  81.         {
  82.             array_push($sheep, 0);
  83.         }else if($value==5)
  84.         {
  85.             unset($sheep[$key]);
  86.         }
  87.     }
  88.     echo $i."==".count($sheep)."
    "
    ;
  89. }
  90. ?>
阅读(2314) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~