Learn Golang in Days - Day 13
简介
- 递归
- 递归,就是自己调用自己
- Go语言支持递归
- 类型转换
递归的应用
package main
import "fmt"
func Factorial(n uint64)(result uint64) {
if(n > 0) {
result = n * Factorial(n-1)
}
return 1
}
func main() {
var i int =15
fmt.Printf("%d 的阶乘是 %d\n", i, Factorial(uint64(i)))
}
斐波那契数列
- 通过Go语言的递归函数实现斐波那契数列
package main
import "fmt"
func fibonacci(n int) int {
if n < 2 {
return n
}
return fibonacci(n-2) + fibonacci(n-1)
}
func main() {
var i int
for i = 0; i < 10; i++ {
fmt.Printf("%d\t", fibonacci(i))
}
}
类型转换
- 类型转换
package main
import "fmt"
func main() {
var sum int = 18
var count int = 5
var mean float32
mean = float32(sum) / float32(count)
fmt.Printf("%f / %d = %f", float32(sum), count, mean)
}
有疑问加站长微信联系(非本文作者)