美文网首页
GO学习 for循环

GO学习 for循环

作者: 3天时间 | 来源:发表于2022-05-07 17:12 被阅读0次

for循环语句

package    main

import    "fmt"

funcmain(){

/*

  1.标准语法:

    for循环:某些代码会被多次执行

    语法:

      for 表达式1;表达式2;表达3{

        循环体

      }

  2.同时省略表达式1和表达式3 (相当于while(条件))

    for 表达式2{

    }

  3.同时省略3个表达式 (相当于while(true))

    for {

    }

  4.其他的写法:for循环中同时省略几个表达式都可以

    省略表达式1:

    省略表达式2:循环永远成立,死循环

    省略表达式3:

  */

//fmt.Println("hello world!")

//fmt.Println("hello world!")

//fmt.Println("hello world!")

//fmt.Println("hello world!")

//fmt.Println("hello world!")

//标准写法

fmt.Println("标准写法")

fori :=1;i <=5;i++{    

fmt.Println("hello world!") 

 }

//同时省略表达式1和表达式3

fmt.Println("同时省略表达式1和表达式3")  

i :=1

fori <=5{    

fmt.Println(i)    

i++  

}  

fmt.Println("-->",i)

//死循环

fmt.Println("死循环,无限执行下去")

for{    

fmt.Println("i-->",i)    

i++  }

}

运行输出:

标准写法

helloworld!

helloworld!

helloworld!

helloworld!

helloworld!

同时省略表达式1和表达式3

1

2

3

4

5

-->6

Processfinishedwithexitcode0

for练习

package    main

import    "fmt"

func    main(){

/*

  for循环的练习题

  练习1:打印58-23数字

  练习2:求1-100的和

  练习3:打印1-100内,能够被3整除,但是不能被5整除的数字,统计被打印的数字的个数,每行打印5个

  */

fmt.Println("练习1:打印58-23数字")

fori :=58; i >=23;i--{    

    fmt.Println(i)  

}  

fmt.Println("练习2:求1-100的和")  

sum :=0

for    i :=1;i <=100;i++{   

     sum = sum + i  

}  

fmt.Println("1-100的和是:",sum)  

fmt.Println("练习3:打印1-100内,能够被3整除,但是不能被5整除的数字,统计被打印的数字的个数,每行打印5个")  

count :=0

for    i :=1;i <=100;i++{

    if    i %3==0    &&     i %5   !=0{      

                fmt.Print(i,"\t")      

                count++

                if    count %5==0{

                            fmt.Println()      

                        }    

                }  

}  

fmt.Println("1-100内,能够被3整除,但是不能被5整除的数字总数为:",count)}

运行输出:

练习1:打印58-23数字

58

57

56

55

54

略。。。

25

24

23

练习2:求1-100的和1-100的和是:5050练习3:打印1-100内,能够被3整除,但是不能被5整除的数字,统计被打印的数字的个数,每行打印5个

3    6    9    12    18

21    24    27    33    36    

39    42    48    51    54    

57    63    66    69    72    

78    81    84    87    93    

96    99    1-100内,能够被3整除,但是不能被5整除的数字总数为:27

Processfinishedwithexitcode0

读完点个赞,给我的坚持更新注入新的活力。

2022.05.07 日更 63/365 天

公众号:3天时间

往期同类文章:

GO学习 switch用法

GO学习 if嵌套和其他用法

GO学习 if和if_else

相关文章

网友评论

      本文标题:GO学习 for循环

      本文链接:https://www.haomeiwen.com/subject/sxexurtx.html