最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

PHP迭代器實(shí)現(xiàn)斐波納契數(shù)列的函數(shù)

 更新時(shí)間:2013年11月12日 10:00:41   作者:  
斐波納契數(shù)列通常做法是用遞歸實(shí)現(xiàn),當(dāng)然還有其它的方法。這里現(xiàn)學(xué)現(xiàn)賣(mài),用PHP的迭代器來(lái)實(shí)現(xiàn)一個(gè)斐波納契數(shù)列,幾乎沒(méi)有什么難度,只是把類(lèi)里的next()方法重寫(xiě)了一次。注釋已經(jīng)寫(xiě)到代碼中,也是相當(dāng)好理解的

復(fù)制代碼 代碼如下:

class Fibonacci implements Iterator {
    private $previous = 1;
    private $current = 0;
    private $key = 0;

    public function current() {
        return $this->current;
    }

    public function key() {
        return $this->key;
    }

    public function next() {
  // 關(guān)鍵在這里
  // 將當(dāng)前值保存到  $newprevious
        $newprevious = $this->current;
  // 將上一個(gè)值與當(dāng)前值的和賦給當(dāng)前值
        $this->current += $this->previous;
  // 前一個(gè)當(dāng)前值賦給上一個(gè)值
        $this->previous = $newprevious;
        $this->key++;
    }

    public function rewind() {
        $this->previous = 1;
        $this->current = 0;
        $this->key = 0;
    }

    public function valid() {
        return true;
    }
}

$seq = new Fibonacci;
$i = 0;
foreach ($seq as $f) {
    echo "$f ";
    if ($i++ === 15) break;
}


程序運(yùn)行結(jié)果:
復(fù)制代碼 代碼如下:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610

相關(guān)文章

最新評(píng)論

光泽县| 金塔县| 留坝县| 大安市| 宿迁市| 金华市| 台前县| 涟源市| 民县| 庆云县| 黎川县| 班戈县| 三原县| 澎湖县| 阿克苏市| 牙克石市| 胶州市| 滨州市| 涞水县| 错那县| 宜昌市| 灌南县| 云龙县| 郴州市| 红安县| 兴安盟| 集安市| 云浮市| 望都县| 江津市| 图片| 方城县| 马边| 林周县| 正阳县| 石柱| 新田县| 和田县| 苏州市| 荆州市| 沐川县|