PHP 迭代器实现斐波那契数列的函数代码
PHP 迭代器实现斐波那契数列的函数代码如下: class Fibonacci Implements Iterator {
private $previous = 1;
private $当前=0;
private $key = 0;
private $previous = 1;
private $当前=0;
private $key = 0;
publi c function current() {
return $this->current;
}
publi c function key() {
return $this> key ;
}
publi c function next() {
// 关键在这里
// 将当前值保存到 $newprevious
$newprevious = $this->current ;
// 将前一个值与当前值之和赋给当前值
$this->current += $this->previous;
// 将前一个当前值赋给前一个值
$this - >previous = $newprevious;
$this->key++;
}
publi c 函数 rewind() {
$this->previous = 1; this ->current = 0;
$this->key = 0;
}
publi c 函数 valid() {
return true;
}
}$seq 斐波那契 ;
$i = 0;
foreach ($seq as $f) {
echo "$f ";
if ($i++ === 15) break;
}
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。