Go core development study notes (X) - loop control

Loop control

  1. While the absence and do ... while Golang language, there is only for, for can replace the while loop format, or continue through the addition of break out of the loop.

  2. for basic format:

    for \<循环变量初始化>;<循环条件>;<循环变量迭代> {
     			\<循环体>
     		}
    

    Example 1:

    for i := 1 ; i < = 10 ; i++ {
    	\<循环体>
    }
    

    Example 2:

    var i int = 1
    for i ;  i < = 10 ; i++ {
    	\<循环体>
    }
    

    Example 3:

    for {                  //实际上等同于 for ; ; {...},也就是 for <空值>;<空值>;<空值> {...}
    	var i int = 1
    	if i <= 10 {
    		\<执行语句>
    	} else {
    		break
    	}
    	i++
    }                      //等同于实现了while功能。
    
  3. Note that if the for loop i defined variable independently of each other, then only just within the loop, the code file contains a plurality of the scopes for i ...
    Example 1:

    for i := 1 ; i <= 10 ; i++ {     
    	\<循环体>
    }
    fmt.Println("i的值为: ",i)        //这个编译会报错,因为i只处于循环体作用域,下面全局变量的"i"根本不存在
    

    Example 2:

    i := 1
    for ; i <= 10 ; i++ {     
    	\<循环体>
    }
    fmt.Println("i的值为: ",i)        //这个编译就没有问题了,因为变量在循环体外,作用域是main函数体。
    
  4. Traversing string, each character string extracted, using default byte traversal stepping through, so for utf8 character encoding three bytes after the split garbled
    similar Python, characters in the string may be used string [i ] of the subject way to extract, through the following three examples demonstrate points:
    example 1:

    var str string = "Oh!shit!"           //标准英文字符串
    for i := 0 ; i <= len(str) ; i++ {
    	fmt.Printf("%c",str[i]) 
    }                                     //因为循环是按照byte遍历,所以标准ascii编码的都没有问题,但是如果存在汉字,那么就出现乱码
    

    Example 2:

    var dest string = "oh!shit!踩到狗屎了"     //包含中文了
    str := []rune(dest)
    for i := 0; i <= len(str) ; i++ {
    	fmt.Printf("%v\n",str[i])
    }  
    //使用切片后,按照字符遍历了。使用切片方式结果正确,但是报错 
    //panic: runtime error: index out of range待解决
    

    Example 3: Using the range, this method is most recommended

    var str1 string = "oh!shit!又踩到狗屎了"
     //一般会有一个index和value配合使用,在此直接用下划线_忽略,index为索引
     for _ , value := range str1 {             
     	fmt.Printf("%c\n",value)
     }
    
  5. Case: all print between 1 and 100 is an integer multiple of 9, and these integers and

    package main
    
    import "fmt"
    
    func main() {
    	var i int = 1
    	var sum int
    	for ; i <= 100 ; i++ {
    		if i % 9 == 0 {
    			fmt.Printf("%v\t",i)
    			sum += i
    		}
    	}
    	fmt.Println()
    	fmt.Printf("这些数的总和为:%v",sum)
    }
    
  6. Case: Print out the following format 0 + 6 = 61 + 5 = 6 + 0 = 6 ... 6 are linefeed

    package main
    
    import "fmt"
    
    func main() {
    	for i := 0 ; i <= 6 ; i++ {
    		fmt.Printf("%d + %d = 6\n",i,6-i)
    	}
    }
    
  7. Nested loop: recommendations contain up to two nested , or too complex logic, if the loop n times, the outer loop m times, n times so that performs m times *
    Case: dota2 the four teams of Ti: og, eg, ability value lgd, wings, five players each team, each input (0 to 99), each team find average values and the average capacity ability value four clan

    package main
    
    import "fmt"
    
    func main() {
    	/*
    	需求:Ti中4个dota2战队:og,eg,lgd,wings,每个战队五名队员,输入每个人的能力值(0~99)。
    	求每个战队的平均能力值以及四个战队的平均能力值。
    
    	需求分析:
    		目前尚不知道Golang列表循环咋整,因为按照教程没学到!做映射吧也不知道咋做,干脆战队1234吧
    		只要求出每个战队平均能力值,相加之后除以便是四个战队总平均能力值
    		两层嵌套已经很费劲了,稍微不注意就会出错,代码如下
    	 */
    	var totalSum float64
    	for j := 1 ; j <= 4 ; j++ {
    		var memAbil float64
    		var teamSum float64
    		var teamAvg float64
    
    		for i := 1; i <= 5; i++ {
    			fmt.Printf("请输入战队%d的第%d名成员的能力值: \n",j,i)
    			fmt.Scanf("%v",&memAbil)
    			teamSum += memAbil
    			teamAvg = teamSum / 5
    		}
    		fmt.Printf("战队%d的平均能力值为:%f\n",j,teamAvg)
    		totalSum += teamAvg
    	}
    	fmt.Printf("四支战队总的平均能力值为:%f",totalSum / 4)
    }
    
  8. Case: 99 print multiplication table (classic problem)

    package main
    
    import "fmt"
    
    func main() {
    	/*
    	需求:99乘法表
    	1 * 1 = 1
    	1 * 2 = 2	2 * 2 = 4
    	1 * 3 = 3   2 * 3 = 6	3 * 3 = 9
    
    	需求分析:
    	两层循环,分别用变量i,j表示
    	打印肯定是 fmt.Printf("%d * %d = %d") 具体分析三个%d应该对应哪些变量
    	变量定义在main()中,不要直接定义在for循环作用域中
    	 */
    	var j int
    	var i int
    	var num int
    
    	fmt.Println("请输入乘数的最大值:")
    	fmt.Scanf("%d",&num)
    	fmt.Println("乘法表结果如下: ")
    	for j = 1 ; j <= num ; j++ {
    		for i = 1; i <= j; i++ {
    			fmt.Printf("%d * %d = %d\t", i,j,i*j )
    		}
    		fmt.Println()
    	}
    }
    
Published 50 original articles · won praise 18 · views 4019

Guess you like

Origin blog.csdn.net/weixin_41047549/article/details/89638566