做了几个例子,
1. 2位精度内逼近2开方的。
package main import ( "fmt" "math" ) func Sqrt(x float64) float64 { b:=1.00 for z:=1.00;z<math.Trunc(math.Sqrt(2)*math.Pow10(2))/math.Pow10(2);z+=0.01 { b = z - (z*z-x)/(2*z) } return b } func main() { fmt.Println(Sqrt(2)) fmt.Println(math.Trunc(math.Sqrt(2)*math.Pow10(2))/math.Pow10(2)) fmt.Println(math.Sqrt(2)) }
2. 这个例子也很好玩可以看自己的平台
package main import ( "fmt" "runtime" ) func main() { fmt.Print("Go runs on ") switch os := runtime.GOOS; os { case "darwin": fmt.Println("OS X.") case "linux": fmt.Println("Linux.") default: // freebsd, openbsd, // plan9, windows... fmt.Printf("%s.", os) } }
3. 统计词频的
package main import ( "golang.org/x/tour/wc" "strings" ) func WordCount(s string) map[string]int { m := make(map[string]int) for _,value:= range strings.Fields(s) { m[value]+=1 } return m } func main() { wc.Test(WordCount) }
4.自己最满意的一个fibonacci,用闭包实现
package main import "fmt" // fibonacci is a function that returns // a function that returns an int. func fibonacci() func() int { f_slice := make([]int, 2) f_slice = []int{0,1} f_index :=0 return func() int { if f_index >1 { f_slice = append(f_slice,f_slice[f_index-1]+f_slice[f_index-2]) } f_index +=1 return f_slice[f_index-1] } } func main() { f := fibonacci() for i := 0; i < 10; i++ { fmt.Println(f()) } }
5.ip地址转换
package main import "fmt" type IPAddr [4]byte // TODO: Add a "String() string" method to IPAddr. func (m IPAddr) String() string { var ret string for i, value := range m { if i==0 { ret +=fmt.Sprintf("%v",value) } else { ret += fmt.Sprintf(".%v",value) } } return ret } func main() { addrs := map[string]IPAddr{ "loopback": {127, 0, 0, 1}, "googleDNS": {8, 8, 8, 8}, } for n, a := range addrs { fmt.Printf("%v: %v\n", n, a) } }
明天接着更
有疑问加站长微信联系(非本文作者)