go实现斐波那契数列

2019-06-16
0 评论 181 浏览

flag获取命令行参数,指定数值
chan和select结合实现斐波那契数列

package main

import (
	"flag"
	"fmt"
)

func Fib(ch chan<- int, quit <-chan bool) {
	x, y := 1, 1
	for {
		select {
		case ch <- x:
			x, y = y, x
			y = x + y
		case <-quit:
			return
		}
	}
}

func main() {
	var num int
	flag.IntVar(&num, "n", 0, "the number if fibonacci")
	flag.Parse()

	ch := make(chan int)
	quit := make(chan bool)

	go func() {
		fmt.Printf("Fibonacci of %d is :\n",num)
		for i := 0; i < num; i++ {
			n := <-ch
			fmt.Printf("%d ", n)
		}
		fmt.Println()
		quit <- true
	}()

	Fib(ch, quit)

}


标题:go实现斐波那契数列
作者:fish2018
地址:http://www.devopser.org/articles/2019/06/16/1560658242103.html

评论
发表评论