• GO基础知识(条件判断、循环)


    条件判断

    //if else
    package main
    
    import (
    	"fmt"
    )
    
    func main() {
    	if num := 10; num % 2 == 0 { //checks if number is even
    		fmt.Println(num,"is even")
    	}  else {
    		fmt.Println(num,"is odd")
    	}
    	fmt.Println(num)//会报错,因为num的作用域只在if else语句中
    }
    
    
    
    //if  else if.... else
    package main
    
    import (  
        "fmt"
    )
    
    func main() {  
        num := 99
        if num <= 50 {
            fmt.Println("number is less than or equal to 50")
        } else if num >= 51 && num <= 100 {
            fmt.Println("number is between 51 and 100")
        } else {
            fmt.Println("number is greater than 100")
        }
    
    }
    
    //else需要放在if}的同一行
    package main
    
    import (  
        "fmt"
    )
    
    func main() {  
        num := 10
        if num % 2 == 0 { //checks if number is even
            fmt.Println("the number is even") 
        }  
        else {
            fmt.Println("the number is odd")
        }
    } //报错:main.go:12:5: syntax error: unexpected else, expecting }
    

    循环

    //go语言中只有唯一的循环语句for
    package main
    
    import (  
        "fmt"
    )
    
    func main() {  
        for i := 1; i <= 10; i++ {
            fmt.Printf(" %d",i)
        }
    }
    
    
    //break,跳出循环
    package main
    
    import (  
        "fmt"
    )
    
    func main() {  
        for i := 1; i <= 10; i++ {
            if i > 5 {
                break //loop is terminated if i > 5
            }
            fmt.Printf("%d ", i)
        }
        fmt.Printf("
    line after for loop")
    }
    /*
    输出
    1 2 3 4 5  
    line after for loop
    */
    
    
    //continue,跳出当前循环,执行下一次循环
    package main
    
    import (  
        "fmt"
    )
    
    func main() {  
        for i := 1; i <= 10; i++ {
            if i%2 == 0 {
                continue
            }
            fmt.Printf("%d ", i)
        }
    }
    /*输出结果
    1 3 5 7 9
    */
    
  • 相关阅读:
    树链剖分学习笔记(未完)
    VI 配置文件(略全)
    linux之awk
    指针之基础篇
    linux之sed
    sqlplus命令手册
    Leetcode复习: 堆和栈
    leetcode 的shell部分4道题整理
    Regular Expression Matching [leetcode]
    深入浅出JAVA
  • 原文地址:https://www.cnblogs.com/michealjy/p/13090121.html
Copyright © 2020-2023  润新知