五、流程控制

1.分支

(1)If

package main

import "fmt"
func main() {
    var yes string
    fmt.Print("是否有卖西瓜的Y/N:")
    fmt.Scan(&yes)
    fmt.Println("老婆的想法")
    if yes == "Y" || yes == "y" {
        fmt.Println("买十个包子以及一个西瓜")
    } else {
        fmt.Println("买十个包子")
    }
    fmt.Println("老公的想法")
    if yes == "N" || yes == "n" {
        fmt.Println("买十个包子")
    } else {
        fmt.Println("买一个包子")
    }
    var score int
    fmt.Println("请输入你的分数:")
    fmt.Scan(&score)
    if score >= 90 {
        fmt.Println("A")
    } else if score >= 80 {
        fmt.Println("B")
    } else if score >= 70 {
        fmt.Println("C")
    } else if score >= 60 {
        fmt.Println("D")
    } else {
        fmt.Println("E")
    }
}

(2)switch

package main

import "fmt"
func main() {
    var yes string
    fmt.Print("是否有卖西瓜的(Y/N):")
    fmt.Scan(&yes)
    switch yes {
    case "y", "Y":
        fmt.Println("老婆的想法:")
        fmt.Println("买一个西瓜以及十个包子")
        fmt.Println("老公的想法")
        fmt.Println("买一个包子")
    default:
        fmt.Println("老婆的想法:")
        fmt.Println("十个包子")
        fmt.Println("老公的想法")
        fmt.Println("买十个包子")
    }
    var score int
    fmt.Print("请输入分数:")
    fmt.Scan(&score)
    switch {
    case score >= 90:
        fmt.Println("A")
    case score >= 80:
        fmt.Println("B")
    case score >= 70:
        fmt.Println("C")
    case score >= 60:
        fmt.Println("D")
    default:
        fmt.Println("E")
    }
}

2.for循环的四种表达方式

package main

import "fmt"
func main() {
    //初始化子语句;条件子语句;后置子语句
    result := 0
    for i := 1; i <= 100; i++ {
        result += i
    }
    fmt.Println(result)
    //go里面没有while循环 但是支持这种写法
    result = 0
    i := 1
    for i <= 100 {
        result += i
        i++
    }
    fmt.Println(result)
    //go里面死循环的写法
    i = 1
    for {
    fmt.Println(i)
    i++
    }
    //字符串,数组,切片,映射,管道
    desc := "我爱中国"
    for i, ch := range desc {
        fmt.Printf("%T %d %q\n", ch, i, ch)
    }
}

3.跳转(goto)

package main

import "fmt"
func main() {
BREAKEND:
    //goto  跳转
    for i := 0; i <= 5; i++ {
        for j := 0; j <= 5; j++ {
            if i*j == 9 {
                break BREAKEND
            }
            fmt.Println(i, j)
        }
    }
    i := 0
    b := 1
START:
    if b > 100 {
        goto STOP
    }
    i += b
    b++
    goto START
STOP:
    fmt.Println(i)
}

4.break&continue

break 表示跳出循环
continue表示跳过本次循环
当然这里也可以使用 label但是label必须定义在循环上面

发布了92 篇原创文章 · 获赞 12 · 访问量 5700

猜你喜欢

转载自blog.csdn.net/weixin_45413603/article/details/104636485
今日推荐