go的rand.Intn()用法和猜年龄, rand.Int()和字符串反转
rand.Intn()用法和猜年龄
package main
import (
"fmt"
"math/rand"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func main() {
target := rand.Intn(101)
count := 0
cur := -1
for cur != target {
fmt.Scanf("%d", &cur)
count++
if cur == target {
fmt.Println("恭喜你,猜对了。")
} else if cur < target {
fmt.Println("猜小了。")
} else {
fmt.Println("猜大了。")
}
}
fmt.Printf("你一共猜了:%d次\n", count)
}
rand.Int()和字符串反转
package main
import (
"fmt"
"math/rand"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func reverse(str string) string {
/*
//方式一
var result string
strLen := len(str)
for i := 0; i < strLen; i++ {
result += fmt.Sprintf("%c", str[strLen-i-1])
}
return result
*/
/*
//方式二
tmp := []byte(str)
var result string
for i := len(str)-1; i >= 0; i-- {
result = result + fmt.Sprintf("%c", tmp[i])
}
return result
*/
//方式三
var result []byte
tmp := []byte(str)
fmt.Printf("你好啊tmp%#v\n", tmp)
length := len(str)
for i := 0; i < length; i++ {
result = append(result, tmp[length-i-1])
}
fmt.Printf("你好啊tmp2>>%#v\n", tmp)
return string(result)
}
func main() {
for i := 1; i <= 10; i++ {
fmt.Printf("rand.Int()=%d,i=%d>>\n",rand.Int(),i)
fmt.Printf("rand.Intn(100)=%d,i=%d>>\n",rand.Intn(100),i)
fmt.Printf("rand.Float32()=%f,i=%d>>\n",rand.Float32(),i)
fmt.Println()
//fmt.Println(rand.Float32())
}
str := "hello world"
fmt.Println(reverse(str))
}
写入自己的博客中才能记得长久