一、for循环语法:
for 循环变量初始化;循环条件;循环变量迭代{
循环体
}
案例:
打印10句hello
方式一
package main
import "fmt"
func main() {
for i := 0;i<10;i++{ //先打印hello后自身+1,for里定义的变量只能在for里使用,有效
fmt.Print("hello")
}
方式二
j := 0
for j<=10{
fmt.Print("hello")
j++
}
方式三:t=通常配合beark来使用
k := 0
for { //等价于 for ; ;{
if k<=10{
fmt.Print("hello")
}else {
break
}
k++
}
案例:打印1-100所有9的倍数的整数及总和
var(
max int = 100
count int = 0
sum int = 0
i int =1
)
for ; i<=max;i++{
if i%9==0{
count+=1
sum+=i
}
}
fmt.Print(count,sum)
案例:求所有两数之和是6的数
var n int =6
for i:=0;i<=n;i++{
fmt.Printf("%v+%v+%v\n",i,n-i,n)
}
效果如下
0+6=6
1+5=6
2+4=6
3+3=6
4+2=6
5+1=6
6+0=6
}
原文:https://www.cnblogs.com/puti306/p/11415711.html