源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2020-06-16 17:44 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:PHP迭代器实现斐波纳契数列的函数
[u]复制代码[/u] 代码如下:
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; }
程序运行结果:
[u]复制代码[/u] 代码如下:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部