练习题
Golang练习题
HelloWorld
func main() { fmt.Println("HelloWorld") }
99乘法表
func main() { for i := 1;i<10;i++ { for j := 1;i<=i;j++ { fmt.Println("%d * %d = %d\t",j,i,j*i) } fmt.Println() }
质数判断
func justfy(a int) bool { for i := 2;i<a;i++ { if a % i == 0{ return false } } return true } func main() { for i:=2;i<100;i++ { if justfy(i) == true { fmt.Printf("[%d] is prime\n",i} } } }
水仙花数,1的立方+5的立方+3的立方=153
func shuixianhua(a int) bool { first := a%10 second := (a/10)%10 third := (a/100)%10 sum := first*first*first+second*second*second+third*third*third if sum == a{ return true } reutrn false } func main() { for i := 100;i<1000;i++{ if shuixianhuashu(i) == true{ fmt.Printf("[%d]是水仙花数\n",i) } } }
字符统计::输入一行字符,统计出英文字母、空格、数字和其他字符的个数
func test(str string) (charCount,numCount,spaceCount,otherCount int) { uftChars := []rune(str) for i:= 0;i<len(uftChars);i++ { if uftChars[i] >= 'a' && uftChars[i] <= 'z' || uftChars[i] >= 'A' && uftChars[i] <= 'Z' { charCount++ continue } if uftChars[i] >= '0' && uftChars[i] <='9' { numChount++ continue } if uftChars[i] == ' '{ spaceConut++ continue } otherCount++} } return } func main() { var str string = "dksjfhk 我123+---" carCount,numCount,spCount,other := test(str) fmt.Printf("字母有%d,数字有%d,空格有%d,其他有%d", charCount, numCount, spCount, other) }
插入排序
func inser_sort(a [8]int) [8]int { for i:=1;i<len(a);i++ { for j:= i;j>0;j-- { if a[j] <a[j-1] { a[j],a[j-1] = a[j-1],a[j] } else { break } } } return a } func main() { var i [8]int = [8]int{8,3, 2, 9, 4, 6, 10, 0} j := inser_sort(i) fmt.Println(i) //[8,3, 2, 9, 4, 6, 10, 0] fmt.Println(j) //[0,2,3,4,6,8,9,10] }
选择排序
func selet_sort(a [8]int) [8]int { for i:=0;i<len(a);i++ { for j:= i+1;j<len(a);j++ { if a[j] < a[i] { [i],a[j] = a[j],a[i] } } } return a } func main() { var i [8]int = [8]int{8, 3, 2, 9, 4, 6, 10, 0} j := select_sort(i) fmt.Println(i) //[8, 3, 2, 9, 4, 6, 10, 0] fmt.Println(j) //[0,2,3,4,6,8,9,10] }
斐波那锲数列
//递归 func fab(n int) int{ if n<=1 { return 1 } return fab(n-1) + fab(n-2) } func main() { for i :=0;i<10;i++ { n:= fab(i) fmt.Println(n) } }
冒泡排序
func select_sort(a [8]int) [8]int{ for i:= 0;i<len(a);i++ { for j:=0;j<len(a)-i-1;j++ { if a[j]>a[j+1]{ a[j],a[j+1] = a[j+1],a[j] } } } return a } func main() { var i [8]int = [8]int{8, 3, 2, 9, 4, 6, 10, 0} j := select_sort{i} fmt.Println(i) fmt.Println(j) }
数组元素之和
func main() { a := [...]int{1,3,5,6,8} b := 0 for _,value := range a { b += value } fmt.Println(b) }
数组中和为给定值的两个元素的下标:数组[1,3,4,8,7]中找出和为8的下标分别是(0,4)和(1,2)
func main() { a := [...]int{1,2,3,4,5,8,4,4,2} for i:=0;i<len(a);i++ { for j:= i+1;j<len(a);j++ { if a[i]+a[j] == 8 { fmt.Printf("(%d,%d)的和等于8\n",i,j) } } } }
切片程序输出
func main() { var sa = make([]string,5,10) for i := 0;i<5;i++ { sa = append(sa,fmt.Sprintf("%v",i)) } fmt.Println(sa) } //[ 0,1,2,3,4,5,6,7,8,9]
sort排序包对数据进行排序
func main() { var a [5]int = [5]int{1,4,2,5,6} sort.Ints(a[:]) //Ints表示整型 fmt.Println(a) var b [5]string = [5]string{"ac","ed","sd","fg"} sort.Strings(b[:]) //Strings表示字符串类型 fmt.Println(b) } //Float64表示浮点型
统计字符串中每个单词出现的次数
//端口 func test(str string) map[string]int { var result mapp[string]int = make(map[string]int,128) words := strings.Split(str," "} for _,v := range words { count,ok := result[v] if !ok { result[v] = 1 } else { result[v] = count+1 } } return result } func main() { var str = "how do ou do?" result := test(str) fmt.Printf("result%v\n",result) } //文件 type CharCount struct { ChCount INT NumCount int SpaceCount int OtherCount int } func main() { file,err := os.Open("c:/test.log") if err != nil { fmt.Println("read file err:",err) return } defer file.Close() var count CharCount reader := bufio.NewReader(file) for { str,err := reader.ReadString('\n') if err == io.EOF { break } if err == ! nil { fmt.printf("read file failed,err:%v",err) break } runeArr := []rune(str) for _,v := range runeArr { switch { case v > ='a' && v<='z': fallthrouth //满足这个条件的无条件执行下一个case内容 case v >= 'A'&&v<='Z': count.ChCount++ case v==' '||v=='\t': count.SpaceCount++ case v>='0'&&v<='9': count.NumCount++ default: count.OtherCount++ } } } fmt.Printf("char count:%d\n",count.ChCount) fmt.Printf("num count:%d\n",count.NumCount) fmt.Printf("space count:%d\n",count.SpaceCount) fmt.Printf("other count:%d\n",count.OtherCount) }
存储学生信息
//学生有id、年龄、分数、需要方便通过id查到对应学生的信息 func test() { var stuMap map[int]map[string]interface{} stuMap = make(map[int]map[string]interface{},16) var id = 1 var name = "stu01" var score = 79.3 var age = 19 value,ok := stuMap[id] if !ok { value = make(map[string]interface{},8) } value["id"] = id value["name"] = name value["score"] = score value["age"] = age stuMap[id] = value fmt.Printf("stuMap:%v\n",stuMap) //stuMap:map[1:mao[age:19 id:1 name:stu01 score:79.3]] 带#表示要输出类型 fmt.Printf("stuMap:%#v\n",stuMap) //stuMap:mao[int]mao[string]interface{}{1:map[string]interface{}{"age":18,"id":1,"name":"stu01","score":79.3}} for i:= 0;i<10;i++ { value,ok := stuMap[i] if !ok { value = make{map[string]interface{},8) } value["name"] = fmt.Sprintf("stu%d",i) value["id"] = i value["score"] = rand.Float32()*100.0 value["age"] = rand.Intn(100) stuMap[i] = vaue } fmt.Println() for k,v := range stuMap { fmt.Printf("id=%d stu info = %#v\n",k,v) } }
struct链表:单向链表
//尾部添加 type Student struct { Name string Age int Score float64 next *Student } func trans(p *Student) { for p!= nil { fmt.Println(*p) p = p.next } fmt.Println() } func test() { var head Student head.Name = "yang" head.Age = 19 head.Score 100.00 var tail = &head for i:=0;i<5;i++ { stu := &Student{ Name : fmt.Sprintf("stu%d",i), Age:rand.Intn(100) Score:rand.Float64() *100, } tail.next = stu tail = stu } trans(&head) } //头部添加 type Stident struct { Name string Age int Score float64 next *Student } func trans(p *Student) { for p!= nil { fmt.Println(*p) p = p.next } fmt.Println() } func test() { var head *Student = &Student{} head.Name = "hua" head.Age = 18 head.Score = 100 for i := 0;i<5;i++ { stu := Student{ Name : fmt.Printf("stu%d",i), Age : rand.Intn(100), Score:rand.Float64() *100, } stu.next = head head = &stu } trans(head) }
defer练习
func f1() int{ x:= 5 defer func() { x++ }() return x } func f2() (x int) { defer func() { x++ }() return 5 } func f3() (y int) { x := 5 defer func() { x++ }() return x } func f4() (x int) { defer func(x int) { x++ }(x) return 5 } func main () { fmt.Println(f1()) //5 fmt.Println(f2()) //6 fmt.Println(f3()) //5 fmt.Println(f4()) //5 }
并发引起的闭包
//问题 var wg sync.WaitGroup func main() { wg.Add(1000) for i :=0;i<1000;i++ { go func() { fmt.Println(hello",i) wg.Done() }() } wg.Wait() } //会有很多重复的1000,匿名函数中i存在调用外部变量的情况产生闭包 //解决 var wg synv.WaitGroup func main() { wg.Add1000) for i:=0;i<1000;i++ { go func(i int) { fmt.Println("hello",i) wg.Done() }(i) } wg.Wait() } //把i传进去就会解决嗲用外部变量的问题
简单聊天机器人
package main import ( "bufio" "fmt" "os" "strings" ) func main() { //从标准输入读取数据 inputReader := bufio.NewReader(os.Stdin) fmt.Println("Please input your name:") //读取数据直到遇见\n位置 input, err := inputReader.ReadString('\n') if err != nil { fmt.Printf("An error occurred:%s\n", err) //异常错误后退出 os.Exit(1) } else { //用切片操作删除最后的\n name := input[:len(input)-1] fmt.Printf("Hello,%s!What can i di for you?\n", name) } for { input, err = inputReader.ReadString('\n') if err != nil { fmt.Printf("An error occurred:%s\n", err) continue } input = input[:len(input)-1] //全部转换为小写 input = strings.ToLower(input) switch input { case "": continue case "nothing", "bye": fmt.Println("Bye!") //正常退出 os.Exit(0) default: fmt.Println("Sorry,I didn't catch you.") } } }
二分查
//存在多个重复元素的切片中查找元素并返回最大的角标 func BinarySearch(s []int, k int) int { lo, hi := 0, len(s)-1 for lo <= hi { m := (lo + hi) >> 1 if s[m] < k { lo = m + 1 } else if s[m] > k { hi = m - 1 } else { if s[m+1] == k { lo = lo + 1 } else { return m } } } return -1 } func main() { s := []int{0, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 6, 6, 6, 7, 7, 7, 8, 9} fmt.Println(BinarySearch(s, 1)) }
股票购买手续费计算
package main import "fmt" func In(n,z float32,tuichu *bool){ //买入时需要的费用 if *tuichu == false { //判断如果变量为false,则退出到主函数 return } var nn,mm,zz float32 fmt.Println("请输入买入几手股份(1手=100股)") fmt.Scanf("%f\n",&nn) fmt.Println("请输入买入价格") fmt.Scanf("%f\n",&mm) nn = nn*100 //将几手转为几百股 zz = nn*mm //买入需要的总价 //计算手续费 if zz*0.0003<5 { zz = zz+5 zz = zz*0.00002+zz shou := zz*0.00002+5 fmt.Printf("手续费:%.3f\n",shou) }else { zz = zz*0.0003+zz zz = zz*0.00002+zz shou := zz*0.0003+zz*0.00002 fmt.Printf("手续费:%.3f\n",shou) } //买入后持仓 z = z+zz n = n+nn fmt.Printf("买入后持仓价为%.3f,持仓%.1f股,买入费用%.3f\n",z/n,n,zz) for{ var c int fmt.Println("继续买入选择1,卖出选择2,返回选择3") fmt.Scanf("%d\n", &c) if c == 1 { In(n, z,tuichu) //递归 return //结束此循环 } else if c == 2 { Out(n, z,tuichu) //递归 return //结束此循环 } else if c == 3{ *tuichu = false //退出时更改全局变量 return //结束此循环 } else { fmt.Println("输入错误") //继续循环 } } } func Out(n,z float32,tuichu *bool) { //卖出时需要的费用 if *tuichu == false { return } var nnn,mmm,zzz,s float32 fmt.Println("请输入卖出几手股份(1手=100股)") fmt.Scanf("%f\n",&nnn) nnn = nnn*100 if nnn > n{ fmt.Println("没那么多股份") return } fmt.Println("请输入卖出价格") fmt.Scanf("%f\n",&mmm) zzz = nnn*mmm n = n-nnn z = z-zzz z = z/n s = zzz*0.001 if zzz*0.0003<=5 { s = s+5 s = zzz*0.00002+s fmt.Printf("手续费:%.3f\n",s) }else { s = zzz*0.0003+s s = zzz*0.00002+s fmt.Printf("手续费:%.3f\n",s) } zzz = zzz-s if n == 0 { z = 0 } //卖出后持仓 fmt.Printf("卖出后持仓价格为%.3f,卖出价格为%.3f\n",z,zzz) for{ var c int fmt.Println("买入选择1,继续卖出选择2,返回选择3") fmt.Scanf("%d\n",&c) if c == 1 { In(n, z,tuichu) return } else if c == 2 { Out(n, z,tuichu) return } else if c == 3{ *tuichu = false return }else { fmt.Println("输入错误") } } } func main(){ for{ tuichu := true //定义变量,控制递归退出 fmt.Println("计算做T、补仓、平仓所需要的手续费") var n, m, z float32 var c int fmt.Println("输入拥有几手股份(1手=100股),还未持仓输入0") fmt.Scanf("%f\n", &n) if n == 0 { //如果未持仓直接跳转买入函数 In(0,0,&tuichu) //指针传递变量,否则无法更改变量 } fmt.Println("输入现在持有价格") fmt.Scanf("%f\n", &m) n = n * 100 z = n * m fmt.Printf("目前持有总价为%.3f\n", z) fmt.Println("买入选择1,卖出选择2") fmt.Scanf("%d\n", &c) if c == 1 { In(n, z,&tuichu) //跳转买入函数,指针传递变量,否则无法更改变量 } else if c == 2 { Out(n, z,&tuichu) //跳转卖出函数,指针传递变量,否则无法更改变量 } else { fmt.Println("输入错误") } } }