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

2018-02-0206:05:12后端程序开发Comments2,270 views字数 551阅读模式
PHP迭代器实现斐波纳契数列的函数代码如下:
class Fibonacci implements Iterator {
private $previous = 1;
private $current = 0;
private $key = 0;文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/348.html

public function current() {
return $this->current;
}文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/348.html

public function key() {
return $this->key;
}文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/348.html

public function next() {
// 关键在这里
// 将当前值保存到 $newprevious
$newprevious = $this->current;
// 将上一个值与当前值的和赋给当前值
$this->current += $this->previous;
// 前一个当前值赋给上一个值
$this->previous = $newprevious;
$this->key++;
}文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/348.html

public function rewind() {
$this->previous = 1;
$this->current = 0;
$this->key = 0;
}文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/348.html

public function valid() {
return true;
}
}$seq = new Fibonacci;
$i = 0;
foreach ($seq as $f) {
echo "$f ";
if ($i++ === 15) break;
}文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/348.html

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/348.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/348.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定