zoukankan      html  css  js  c++  java
  • 输出斐波纳契数列

    方法一:迭代器
    class myIterator implements Iterator {
        private $position = 0;
        private $current = 1;
        private $previous = 0;
    
        public function __construct(){}
    
        public function rewind()
        {
            $this->position = 0;
            $this->current = 1;
            $this->previous = 0;
        }
    
        public function current()
        {
            return $this->current;
        }
    
        public function key()
        {
            return $this->position;
        }
    
        public function next()
        {
            $tem = $this->previous;
            $this->previous = $this->current;
            $this->current = $this->current + $tem;
            ++$this->position;
        }
    
        public function valid()
        {
            return ($this->current !== false);
        }
    }
     
    $it = new myIterator;
    foreach($it as $key => $value) {
        // if ($key > 15) break;
        echo "$value    ";
    }
    
    方法二:生成器
    function generator()
    {
        $current = 1;
        $previous = 0;
        while ($current) {
            yield $current; // 重点在这里使用了yield
            $temp = $current;
            $current = $current + $previous;
            $previous = $temp;
        }
    }
    
    foreach (generator() as $key => $value) {
        // if ($key > 15) break;
        echo "$value    ";
    }
    
  • 相关阅读:
    python 文件 笔记
    python 模块、包 笔记
    类、对象
    python 函数 笔记
    测试价值体现
    断舍离-笔记2
    Happy 2006 POJ
    Triangle War POJ
    Complete the sequence! POJ
    放苹果 POJ
  • 原文地址:https://www.cnblogs.com/phonecom/p/10345743.html
Copyright © 2011-2022 走看看