网络编程 
首页 > 网络编程 > 浏览文章

PHP迭代器实现斐波纳契数列的函数

(编辑:jimmy 日期: 2024/10/13 浏览:3 次 )

复制代码 代码如下:
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 SPL使用方法和他的威力
一句话新闻
Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。