当前位置:网站首页>学习 Go 语言 0x06:《Go 语言之旅》中 斐波纳契闭包 练习题代码
学习 Go 语言 0x06:《Go 语言之旅》中 斐波纳契闭包 练习题代码
2022-04-23 11:02:00 【爱博客大伯】
* 题目
https://tour.go-zh.org/moretypes/26
练习:斐波纳契闭包
实现一个 fibonacci 函数,它返回一个函数(闭包),该闭包返回一个斐波纳契数列 (0, 1, 1, 2, 3, 5, ...)。
* 代码
package main
import "fmt"
// 返回一个“返回int的函数”
func fibonacci() func() int {
a := 0
b := 1
return func() int {
ret := a
a = b
b = b + ret
return ret
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
输出:
0
1
1
2
3
5
8
13
21
34
对代码稍作改动,如下:
package main
import "fmt"
// 返回一个“返回int的函数”
func fibonacci() func() int {
a := 0
b := 1
return func() int {
ret := a
a, b = b, a + b // 更改了这里,两个变量的更新写在一行中
return ret
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
版权声明
本文为[爱博客大伯]所创,转载请带上原文链接,感谢
https://blog.csdn.net/u013553529/article/details/88903952
边栏推荐
- Visual solutions to common problems (VIII) mathematical formulas
- 《Neo4j权威指南》简介,求伯君、周鸿袆、胡晓峰、周涛等大咖隆重推荐
- Latex usage
- Excel·VBA自定义函数获取单元格多数值
- UEditor之——图片上传组件大小4M的限制
- 主流手机分辨率与尺寸
- Learning Notes 6 - Summary of several deep learning convolutional neural networks
- Chapter 120 SQL function round
- VIM + ctags + cscope development environment construction guide
- [Niuke challenge 47] C. conditions (BitSet acceleration Floyd)
猜你喜欢

After the MySQL router is reinstalled, it reconnects to the cluster for boot - a problem that has been configured in this host before

Visualized common drawing (II) line chart

Solutions to common problems in visualization (IX) background color

Promise详解

精彩回顾|「源」来如此 第六期 - 开源经济与产业投资

SVN的使用:

Go interface usage

How can swagger2 custom parameter annotations not be displayed

Download and installation steps of xshell + xftp

《Neo4j权威指南》简介,求伯君、周鸿袆、胡晓峰、周涛等大咖隆重推荐
随机推荐
Understand the key points of complement
C语言之结构体(进阶篇)
全栈交叉编译X86完成过程经验分享
Pycharm
SQL Server cursor circular table data
Latex usage
Excel·VBA自定义函数获取单元格多数值
How to bind a process to a specified CPU
MBA - day5 mathématiques - Questions d'application - Questions d'ingénierie
SWAT—Samba WEB管理工具介绍
Using El popconfirm and El backtop does not take effect
App. In wechat applet JS files, components, APIs
Mba-day5 Mathematics - application problems - engineering problems
如何使用JDBC CallableStatement.wasNull()方法调用来查看最后一个OUT参数的值是否为 SQL NULL
The courses bought at a high price are open! PHPer data sharing
CUMCM 2021-B:乙醇偶合制备C4烯烃(2)
MySQL common statements
Facing the global market, platefarm today logs in to four major global platforms such as Huobi
How does the swagger2 interface import postman
Strongest date regular expression