您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2025/12/22 8:04:42发布11次查看
复制代码 代码如下:
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
http://www.bkjia.com/phpjc/825140.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/825140.htmltecharticle复制代码 代码如下: class fibonacci implements iterator { private $previous = 1; private $current = 0; private $key = 0; public function current() { return $this-current; }...
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product