Section 13.3 Go Exercises

Section 13.3 Go Exercises

Exercise 1: Defining an integer, a small number, access to the variable values ​​and print type, change the value of a variable, print value

Exercise 2: also defines three integers,

Exercise 3: also defines three strings

Exercise 4: After you define a variable, no initial value, direct access variables?

Exercise 5: Try to define global variables

Exercise 6: Constant group defined constants, assignment and if there is no agreement on a single line, the wording?

package main

import "fmt"

//全局变量,函数体外
var (
    addr  string
    score float64
)

func main() {
    //局部变量,简短声明赋值
    i := 100
    f := 99.9
    fmt.Printf("类型:%T    值%v\n", i, i)
    fmt.Printf("类型:%T    值%v\n", f, f)

    //同时定义三个整数
    n1, n2, n3 := 1, 2, 3
    fmt.Println(n1, n2, n3)
    s1, s2, s3 := "断剑重铸之日", "骑士归来之时", "稳住我能carry"
    fmt.Println(s1, s2, s3)
    fmt.Println(s2)
    fmt.Println(s3)

    //定义变量,默认值,值类型可以修改,引用类型nil不得直接使用
    var name string
    fmt.Println(name)
    var age int
    fmt.Println(age)
    var m map[string]string
    fmt.Println(m)

    //读取全局变量
    addr = "昌平沙河"
    score = 99.99
    fmt.Println(addr)
    fmt.Println(score)

    fmt.Println(".........我是分割线.......")
    //常量定义
    const (
        sunday = iota
        Monday
        Tuesday
        Wedensday = "星期三"
        Thursday  = "星期四"
        Friday    = iota
        Saturday
    )
    fmt.Println(sunday)
    fmt.Println(Tuesday)
    fmt.Println(Friday)
    fmt.Println(Saturday)
}

1. Each basic types of variables, each of the five variables declared, and print variable values, and types.

2. Declare a few constants.

3. The switching values ​​of the two variables.

4. Define a four-digit integer, respectively, obtain the value of each digit

5. Allow the user to enter account password, and accepts user account password

package main

import "fmt"

func main() {
    s1 := "我是字符串" //string
    b1 := 'w'
    var b2 byte = 'w' //byte是uint8的别名
    var b3 rune = '于' //rune是int32的别名,字符本质存的是字节码
    f1 := 123.45
    i1 := 12345678
    b4 := true
    b5 := false
    fmt.Printf("%T %v\n", s1, s1)
    fmt.Printf("%T %v %c\n", b1, b1, b1)
    fmt.Printf("%T %v %c\n", b2, b2, b2)
    fmt.Printf("%T %v %c\n", b3, b3, b3)
    fmt.Printf("%T %v \n", f1, f1)
    fmt.Printf("%T %v \n", i1, i1)
    fmt.Printf("%T %v\n", b4, b4)
    fmt.Printf("%T %v\n", b5, b5)
    fmt.Println("-----分割线----")
    //定义赋值常量
    const pi = 3.1415926
    const (
        Sunday = "星期天"
        Monday = 1
    )
    fmt.Println("-----分割线----")
    //交换变量的值
    a := 3
    b := 2
    a, b = b, a
    fmt.Println(a)
    fmt.Println(b)
    fmt.Println("-----分割线----")
    //定义一个四位数的整数,分别获取各个位数的值
    num1 := 1983
    geWei := num1 % 10
    shiWei := (num1 / 10) % 10
    baiWei := (num1 / 100) % 10
    qianWei := (num1 / 1000) % 10
    fmt.Println(geWei)
    fmt.Println(shiWei)
    fmt.Println(baiWei)
    fmt.Println(qianWei)

    //键盘输入账号密码且打印
    var username string
    var password string
    fmt.Print("输入账号:")
    fmt.Scan(&username)
    fmt.Print("输入密码:")
    fmt.Scan(&password)
    fmt.Printf("用户输入的账号%s,密码%s\n", username, password)
}

1. Use an if statement to complete: a given number: if 1, on Monday output, if it is 2, then the output Tuesday, and so on, up to 7, the output Sunday. If other numbers on the output "error message."

2. Job 1 was changed to switch mode

3. Use the if statement to complete: a given month, this month belongs to which output the season. 3,4,5 6,7,8 Spring Summer Fall 12, 10, 11, 1, 2 winter

4. The operation mode using the switch 3

5. Analog logging in, the user name and password on the keyboard, if the user name is admin password 123, the user name or password is zhangsan zhangsan123, expressed log. Otherwise, print login fails

6. Use the if statement to complete: a given age, if less than 18 years of age, adolescents output, if not less than 18 and younger than 30, the output of young, middle-aged or output.

7. Finish with a simple switch "+ - * /" Calculator

8. random guessing game

Less than 9.100, calculated odd and even and

10. A one hundred one hundred yuan to buy one hundred white chicken chicken, buy one hundred yuan 100 chickens, one rooster 5 yuan, 3 yuan a hen, chicken 1 yuan 3.

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func testIf() {
    var num int
    fmt.Println("请输入数字:1-4")
    fmt.Scan(&num)
    if num == 1 {
        fmt.Println("星期一")
    } else if num == 2 {
        fmt.Println("星期二")
    } else if num == 3 {
        fmt.Println("星期三")
    } else if num == 4 {
        fmt.Println("星期四")
    } else {
        fmt.Println("输入有误,重新输入")
    }
}
func testSwitch() {
    var num int
    fmt.Println("请输入数字:1-4")
    fmt.Scan(&num)
    switch num {
    case 1:
        fmt.Println("星期一")
    case 2:
        fmt.Println("星期二")
    case 3:
        fmt.Println("星期三")
    case 4:
        fmt.Println("星期四")
    default:
        fmt.Println("输入有误,重新输入")
    }
}
func testIf2() {
    var num int
    fmt.Println("请输入月份")
    fmt.Scan(&num)
    if num == 3 || num == 4 || num == 5 {
        fmt.Println("春天来了,又到了...")
    } else if num == 6 || num == 7 || num == 8 {
        fmt.Println("夏天到了,又可以....")
    } else if num == 9 || num == 10 || num == 11 {
        fmt.Println("秋天到了,适合休息,秋游")
    } else if num == 12 || num == 1 || num == 2 {
        fmt.Println("春天到了,万物冬眠")
    } else {
        fmt.Println("输入月份有误")
    }
}
func testSwitch2() {
    var num int
    fmt.Println("请输入月份")
    fmt.Scan(&num)
    switch num {
    case 3, 4, 5:
        fmt.Println("春困")
    case 6, 7, 8:
        fmt.Println("夏乏")
    case 9, 10, 11:
        fmt.Println("秋天适合郊游")
    case 12, 1, 2:
        fmt.Println("冬眠")
    default:
        fmt.Println("输入月份有误")
    }
}
func userPwd() {
    var username string
    var pwd string
    fmt.Println("请输入用户名:")
    fmt.Scan(&username)
    fmt.Println("请输入密码:")
    fmt.Scan(&pwd)
    if username == "oldboy" && pwd == "oldboy666" {
        fmt.Println("登录成功")
    } else {
        fmt.Println("登录失败")
    }
}

func ageTest() {
    var age int
    fmt.Println("请输入你的年纪:")
    fmt.Scan(&age)
    if age < 18 {
        fmt.Println("你好,小老弟")
    } else if age > 18 && age < 30 {
        fmt.Println("你好,青年")
    } else {
        fmt.Println("你个遭老头子,坏得很")
    }
}
func switchCalc() {
    var num1 int
    fmt.Print("输入num1:")
    fmt.Scan(&num1)
    var num2 int
    fmt.Print("输入num2:")
    fmt.Scan(&num2)
    var oper string
    fmt.Println("输入运算符:")
    fmt.Scan(&oper)
    switch oper {
    case "+":
        fmt.Println(num1 + num2)
    case "-":
        fmt.Println(num1 - num2)
    case "*":
        fmt.Println(num1 * num2)
    case "/":
        fmt.Println(num1 / num2)
    default:
        fmt.Println("运算符有误")
    }
}
func caishuzi() {
    /*
        猜数游戏:
        step1:产生随机数
        step2:循环猜数
    */
    //1.产生系统的随机数
    rand.Seed(time.Now().UnixNano())
    randNum := rand.Intn(50)
    //fmt.Println(randNum)

    num := 0
    //2.猜,如果猜不对,一直循环
    for i := 0; num != randNum; i++ {
        fmt.Printf("第%d次输入数字:\n", i)
        fmt.Scan(&num)
        if num > randNum {
            fmt.Println("猜大了")
        } else if num < randNum {
            fmt.Println("猜小了")
        } else {
            fmt.Println("恭喜你,猜对了!!")
        }
    }
}

//100以内,计算奇数和,偶数和
func jiou() {
    //奇数
    num := 0
    num2 := 0

    for i := 0; i < 100; i++ {
        if i%2 == 0 {
            num += i
        }
        if i%2 == 1 {
            num2 += i
        }
    }
    fmt.Println("100以内偶数和:", num)
    fmt.Println("100以内奇数和:", num2)
}

/*
百钱买白鸡
百元百鸡,一百元钱买100只鸡,公鸡5元一只,母鸡3元一只,小鸡1元3个。
100元,一共买100只鸡
公鸡可买数量范围 [0,20]  数量a
母鸡可买数量范围 [0,33]      数量b
最多买100只鸡,所以不可能全部买小鸡,300只超量了
小鸡可买数量范围[100-a-b] 去掉a,b的数量,就是剩下小鸡的数量
*/

func ji() {
    for a := 0; a <= 20; a++ { //公鸡的数量
        for b := 0; b <= 33; b++ { //母鸡的数量
            c := 100 - a - b //小鸡的数量
            //所有组合可能性如下
            //fmt.Printf("公鸡数量%d 母鸡数量%d 小鸡数量%d\n", a, b, c)
            //如果三只鸡的钱总数是100 并且 没有剩余的钱,组合就正确了
            //公鸡价格5元一只,母鸡价格3元一只,小鸡数量3元一个,所以c/3等于价格
            //并且小鸡数量取余3,没有余数,代表没有零钱
            if a*5+b*3+c/3 == 100 && c%3 == 0 {
                fmt.Printf("百钱买白鸡:公鸡数量:%d\t,母鸡数量:%d\t,小鸡数量:%d\n", a, b, c)
            }
        }
    }
}
func main() {
    ji()
}

A group of people, the number between 100-200 1. playground. The trio more than one person, more than two groups of four people, five groups of more than three people. Total number of people asked on the playground.

2. two natural numbers x, y division, commercially than 310, the number of the dividend, the divisor, quotient, a remainder and 163, seeking dividend, divisor

3. a mathematics competition, the number of entries between about 380-450. Results of the competition, all the candidates overall average score of 76 points, an average of 75 boys divided, divided into 80.1 average girls, how many people are seeking boys and girls have.

4. Given an array, arr1: = [10] int sum of all the data {} 5,4,3,7,10,2,9,8,6,1, seeking array.

5. The two-dimensional array traversal

6. Given an integer array, the length of 10. Numbers from a random number.

package main

import (
    "fmt"
    "math/rand"
    "time"
)

//操场人数
func playGround() {
    for i := 100; i <= 200; i++ {
        if i%3 == 1 && i%4 == 2 && i%5 == 3 {
            fmt.Println(i)
        }
    }
}

//
func test1() {
    //    两个自然数x,y相除,商3余10,被除数,除数,商,余数的和是163,求被除数,除数
    /*
        思路:
        自然数x,y加上商,余数总和是163
        条件商3余数10,那么去掉这个数,x+y的总和是150
    */
    for x := 0; x < 150; x++ {
        //y的值
        y := 150 - x
        if x/y == 3 && x%y == 10 {
            fmt.Printf("被除数%d 除数%d\n", x, y)
        }
    }
}

func student() {
    //某数学竞赛中,参赛人数大约在380-450之间。比赛结果,全体考生的总平均分为76分,男生的平均分为75,女生的平均分为80.1,求男女生各有多少人。
    /*
        思路,人数一共380-450之间    i
        求男生数量    x
        女生数量        y
        条件,全体人数平均分76,男生平均分75,女生平均分80.1
    */
    //嵌套循环计算
    for i := 380; i < 450; i++ {
        for x := 0; x < i; x++ {
            y := i - x
            //计算人数
            //总分数=男生分数+女生分数
            if float64(i*76) == float64(x*75)+float64(y)*(80.1) {
                fmt.Printf("男生人数:%d\t女生人数%d\t总人数%d\n", x, y, i)
            }
        }
    }
}

func test2() {
    //给定一个数组,arr1 := [10] int{5,4,3,7,10,2,9,8,6,1},求数组中所有数据的总和。
    arr1 := [10]int{5, 4, 3, 7, 10, 2, 9, 8, 6, 1}
    num := 0
    for _, v := range arr1 {
        num += v
    }
    fmt.Println("数组元素总和", num)
}

//二维数组
/*
二维数组:存储的是一维的一维
        arr :=[3][4]int
        该二维数组的长度,就是3。
        存储的元素是一维数组,一维数组的元素是数值
*/
func test3() {
    arr := [3][4]int{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}} //默认值    [[1 2 3 4] [0 0 0 0] [0 0 0 0]]
    fmt.Println(arr)
    //取出二维数组元素
    for _, v1 := range arr {
        for _, v2 := range v1 {
            fmt.Println("二维数组中的元素:", v2)
        }
    }
}

//给定一个整型数组,长度为10。数字取自随机数。
func makeArray() {
    /*
        给定一个整型数组,长度为10。数字取自随机数。
        [1,10]
    */
    //初始化数组
    arr := [10]int{}
    fmt.Println(arr)
    //随机数种子
    rand.Seed(time.Now().UnixNano())
    //循环生成写入元素,正常写入
    for i := 0; i < len(arr); i++ {

        x := 0
        //验证:x是否已经存储过了
        /*
         循环验证x是否已经存储,如果已经有,再取随机数,再验证,直到不重复
        */
        //循环验证
        for {
            //生成随机数
            x = rand.Intn(10) + 1 // 8
            flag := true          //true:代表不重复值可以用,false代表值重复,不可以使用
            //循环检测,次数依次少于元素个数
            for j := 0; j < i; j++ {
                //如果x元素已经存在,结束循环
                if x == arr[j] {
                    flag = false
                    break
                }
            }
            //如果为真,就停止死循环
            if flag {
                //判断标记的值
                break
            }
        }
        arr[i] = x
    }
    fmt.Println(arr)
}

func main() {
    makeArray()
}

1. Given a pathname: pathName: = " http://192.168.15.33/static/aa.jpeg " Get File Name: aa.jpeg

2. Given a following string: statistics, the number of the number of lowercase letters, uppercase letters of non-alphanumeric number.

str:="aekjffjkJDJ294384848DKFJFJkdjfhfh2943845593nfnJRIEIFJ"

package main

import (
    "fmt"
    "strings"
)

/*
练习2:给定一个路径名:
pathName:="http://192.168.10.1:8080/Day33_Servlet/aa.jpeg"
获取文件名称:aa.jpeg

    给定一个以下字符串:统计大写字母的个数,小写字母的个数,非字母的个数。
str:="aekjffjkJDJ294384848DKFJFJkdjfhfh2943845593nfnJRIEIFJ"
*/

func main() {
    pathName := "http://192.168.10.1:8080/Day33_Servlet/aa.jpeg"
    //取出末尾元素方式一
    //slistStr:=strings.Split(pathName,"/")
    //fmt.Println(slistStr[len(slistStr)-1:])

    //方式二,找到/符号的索引,加一取出
    fileName := pathName[strings.LastIndex(pathName, "/")+1:]
    fmt.Printf("%T %v \n", fileName, fileName)

    //统计个数
    str:="aekjffjkJDJ294384848DKFJFJkdjfhfh2943845593nfnJRIEIFJ"
    count1 := 0
    count2 := 0
    count3 := 0

    for i := 0; i < len(str); i++ {
        if str[i] >= 'A' && str[i] <= 'Z' {
            count1++
        } else if str[i] >= 'a' && str[i] <= 'z' {
            count2++
        } else {
            count3++
        }
    }

    fmt.Printf("大写字母:%d,小写字母:%d,非字母:%d\n", count1, count2, count3)
}

1. Exercise: recursive algorithm factorial 5

2. Exercise: Rabbit Rabbit Health: Fibonacci series: 1, 2 are two values ​​1, starting from the third term is the sum of the first two. Using a recursive algorithm to find the value of the item 12.

func getfactorial(n int)int{
    if n== 1{
        return 1
    }
    return getfactorial(n-1) *n
}

1. a coroutine 100 digital printing, another coroutine printed letters 100

package main

import (
    "fmt"
    "time"
)

func printNum() {
    for i := 0; i < 100; i++ {
        fmt.Println("goroutine1 打印数字:", i)
        time.Sleep(1 * time.Second)

    }
}

func printChar() {
    for i := 0; i < 100; i++ {
        fmt.Printf("goroutine2 打印【字符】: %c\n", i)
        time.Sleep(1 * time.Second)
    }
}
func main() {
    //如果不加go协程去运行,函数会等待运行
    //加go 并发版运行,抢占式运行,每次结果都不一样
    //可以设置睡眠时间,查看go协程是并发运行
    go printChar()
    go printNum()
    time.Sleep(10 * time.Second)
    fmt.Println("main结束。。。")
}

1. Create and start a child goroutine, 100 digital print, to ensure that end before the end of the main goroutine. (Using pipes)

package main

import (
    "fmt"
    "time"
)

//利用chan阻塞的特性,延迟main进程结束
func printNum(ch1 chan bool) {
    for i := 1; i <= 100; i++ {
        fmt.Println(i)
        time.Sleep(10 * time.Millisecond)
    }
    ch1 <- true //写入一个标志位,true
}
func main() {
    //练习1:创建并启动一个子 goroutine,打印100个数字,要保证在main goroutine结束前结束。
    ch1 := make(chan bool)
    printNum(ch1)
    <-ch1 //读取管道数据,如果没读到数据,会一直阻塞,延迟main进程结束
}

Channel 1. Channel Usage examples

package main

import (
    "fmt"
    "time"
)

func main() {
    //go的ok语法
    ch1 := make(chan int)
    go sendData(ch1)

    //channel关闭后不得再写入,可以读取
    //channel如果没关闭,且没有数据,再读取channel会pannic
    //读取数据
    for {
        time.Sleep(1*time.Second)//每秒读一次
        data,ok:=<-ch1//返回值data,与ok布尔值
        if !ok{
            fmt.Println("数据读取完毕,通道已经关闭",ok)
            break
        }
        fmt.Printf("已读取到数据【%d】%v\n",data,ok)
    }
}

func sendData(ch1 chan int) {
    for i := 1; i < 10; i++ {
        ch1 <- i //向通道写入数据
    }
    fmt.Println("数据写入完毕")
    close(ch1)//关闭管道,接收方已经无法取数据
}

Guess you like

Origin www.cnblogs.com/open-yang/p/11256980.html