PHP使用迭代器實現(xiàn)斐波納契數(shù)列的方法

斐波納契數(shù)列通常做法是用遞歸實現(xiàn),當(dāng)然還有其它的方法。這里現(xiàn)學(xué)現(xiàn)賣,用PHP的迭代器來實現(xiàn)一個斐波納契數(shù)列,幾乎沒有什么難度,只是把類里的next()方法重寫了一次。

網(wǎng)站建設(shè)哪家好,找成都創(chuàng)新互聯(lián)公司!專注于網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、微信小程序、集團企業(yè)網(wǎng)站建設(shè)等服務(wù)項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了東勝免費建站歡迎大家使用!

注釋已經(jīng)寫到代碼中,也是相當(dāng)好理解的。

/**
* @author 簡明現(xiàn)代魔法 http://www.nowamagic.net
*/
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; 
// 將上一個值與當(dāng)前值的和賦給當(dāng)前值
        $this->current += $this->previous; 
// 前一個當(dāng)前值賦給上一個值
        $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; 
}

程序運行結(jié)果:

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

以上就是如何用PHP迭代器來實現(xiàn)一個斐波納契數(shù)列的詳細內(nèi)容,更多請關(guān)注創(chuàng)新互聯(lián)其它相關(guān)文章!

文章標(biāo)題:PHP使用迭代器實現(xiàn)斐波納契數(shù)列的方法
文章位置:http://muchs.cn/article12/jehggc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供搜索引擎優(yōu)化、網(wǎng)站制作動態(tài)網(wǎng)站、面包屑導(dǎo)航網(wǎng)站內(nèi)鏈、虛擬主機

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

手機網(wǎng)站建設(shè)