类别:PHP教程 / 日期:2019-12-04 / 浏览:213 / 评论:0

斐波纳契数列一般做法是用递归完成,固然另有别的的要领。这里现学现卖,用PHP的迭代器来完成一个斐波纳契数列,险些没有什么难度,只是把类里的next()要领重写了一次。

解释已写到代码中,也是相当好明白的。

/**
* @author 简明当代魔法 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() { 
// 症结在这里
// 将当前值保存到  $newprevious
        $newprevious = $this->current; 
// 将上一个值与当前值的和赋给当前值
        $this->current += $this->previous; 
// 前一个当前值赋给上一个值
        $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; 
}

顺序运转效果:

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

引荐:《PHP教程》

以上就是如何用PHP迭代器来完成一个斐波纳契数列的细致内容,更多请关注ki4网别的相干文章!

打赏

感谢您的赞助~

打开支付宝扫一扫,即可进行扫码打赏哦~

版权声明 : 本文未使用任何知识共享协议授权,您可以任何形式自由转载或使用。

 可能感兴趣的文章