mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 05:11:49 +08:00
update book code
This commit is contained in:
44
eBook/exercises/chapter_14/gofibonacci.go
Executable file
44
eBook/exercises/chapter_14/gofibonacci.go
Executable file
@@ -0,0 +1,44 @@
|
||||
// Q26_fibonacci_go.go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
term := 25
|
||||
i := 0
|
||||
c := make(chan int)
|
||||
start := time.Now()
|
||||
|
||||
go fibnterms(term, c)
|
||||
for {
|
||||
if result, ok := <-c; ok {
|
||||
fmt.Printf("fibonacci(%d) is: %d\n", i, result)
|
||||
i++
|
||||
} else {
|
||||
end := time.Now()
|
||||
delta := end.Sub(start)
|
||||
fmt.Printf("longCalculation took this amount of time: %s\n", delta)
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func fibnterms(term int, c chan int) {
|
||||
for i := 0; i <= term; i++ {
|
||||
c <- fibonacci(i)
|
||||
}
|
||||
close(c)
|
||||
}
|
||||
|
||||
func fibonacci(n int) (res int) {
|
||||
if n <= 1 {
|
||||
res = 1
|
||||
} else {
|
||||
res = fibonacci(n-1) + fibonacci(n-2)
|
||||
}
|
||||
return
|
||||
}
|
Reference in New Issue
Block a user