文章目錄
- 一、回圈陳述句
- 1. 普通回圈
- 1)語法
- 2)舉例
- 2. 回圈嵌套
- 3. range回圈
- 二、回圈控制陳述句
- 1.Break-中斷(跳出)回圈
- 1)中斷(跳出)回圈
- 2)指定想中斷(跳出)的回圈(嵌套回圈中使用)
- 2.Continue-跳過當次回圈
- 3.goto-條件轉移
一、回圈陳述句
1. 普通回圈
1)語法
for init; condition; post { }
- init(可選):給控制變數賦初值;
- condition(可選):控制條件(不填的時候等于
while True); - post(可選):控制變數增量或減量;
2)舉例
1.求1到10的數字之和,
package main
import "fmt"
func main() {
count := 0
for i := 0; i <= 10; i++ {
count += i
}
fmt.Println("1到10的數字之和為:",count)
}
執行結果
1到10的數字之和為: 55
2.省略init和post:計算count小于10時自相加的值:
package main
import "fmt"
func main() {
count := 1
for ; count < 10; {
count += count
}
fmt.Println("count小于10時自相加的值為:",count)
}
也可以省略;號:
package main
import "fmt"
func main() {
count := 1
for count < 10{ //省略分號
count += count
}
fmt.Println("1到10的數字之和為:",count)
}
執行結果
count小于10時自相加的值為
3.Golang中沒有while回圈,可以通過省略condition來實作:
package main
import "fmt"
func main() {
for { //省略condition
fmt.Println("死回圈")
}
}
2. 回圈嵌套
package main
import "fmt"
func main() {
count := 0
for i := 0; i < 10; i++ {
for j := 0; j <= 10; j++ {
count += j
}
}
fmt.Println("(1到10的數字之和)x10:",count)
}
輸出結果
(1到10的數字之和)x10: 550
3. range回圈
用于對字串、陣列、切片等進行迭代輸出元素:
package main
import "fmt"
func main() {
strArray := []string{"a", "b","c"} //字串陣列
for i,v := range strArray {
fmt.Println(fmt.Sprintf("下標為:%d 值為:%s", i,v))
}
}
輸出結果
下標為:0 值為:a
下標為:1 值為:b
下標為:2 值為:c
二、回圈控制陳述句
1.Break-中斷(跳出)回圈
1)中斷(跳出)回圈
寫一個死回圈,變數a會一直加1,當a的值大于3的時候則跳出回圈:
package main
import "fmt"
func main() {
a := 1
for {
a++
fmt.Printf("a 的值為 : %d\n", a)
if a > 3 {
/* 使用 break 陳述句跳出回圈 */
fmt.Printf("跳出回圈")
break
}
}
}
輸出結果
a 的值為 : 2
a 的值為 : 3
a 的值為 : 4
跳出回圈
2)指定想中斷(跳出)的回圈(嵌套回圈中使用)
使用標號,可以指定想跳出的回圈,
下面是未使用標記,普通break中斷回圈,只會中斷當前層回圈,不會中斷外層,外層列印的值始終為11:
package main
import "fmt"
func main() {
for i := 1; i <= 2; i++ {
fmt.Printf("外層回圈i: %d\n", i)
for j := 11; j <= 12; j++ {
fmt.Printf("內層回圈j: %d\n", j)
break //不使用標記,則只會中斷該層回圈,不會中斷外層回圈
}
}
}
輸出結果
外層回圈i: 1
內層回圈j: 11
外層回圈i: 2
內層回圈j: 11
下面是使用標記,指定中斷外層回圈,等于只回圈執行了一次:
package main
import "fmt"
func main() {
re:
for i := 1; i <= 2; i++ {
fmt.Printf("外層回圈i: %d\n", i)
for j := 11; j <= 12; j++ {
fmt.Printf("內層回圈j: %d\n", j)
break re //使用標記,中斷外層回圈
}
}
}
輸出結果
外層回圈i: 1
內層回圈j: 11
2.Continue-跳過當次回圈
continue 是跳過當次回圈執行后面的回圈,而非中斷回圈
package main
import "fmt"
func main() {
for a := 1; a < 5; a++ {
if a == 3 { //a=3時執行continue跳過
continue
}
//a=3時不會執行列印操作
fmt.Printf("a 的值為 : %d\n", a)
}
}
執行結果
a 的值為 : 1
a 的值為 : 2
a 的值為 : 4
在回圈嵌套時,continue也可以指定跳過的回圈,用法與break一樣
3.goto-條件轉移
goto 可以直接轉移到指定代碼處進行執行,
下面的代碼,當a=3時,會跳出for回圈,直接執行LOOP所在行的代碼:
package main
import "fmt"
func main() {
for a := 1; a < 5; a++ {
if a == 3 { //a等于3;執行goto跳出
goto LOOP
}
//a=3時不會執行列印操作
fmt.Printf("a 的值為 : %d\n", a)
}
LOOP:fmt.Printf("a等于3;執行goto跳出!")
}
執行結果
a 的值為 : 1
a 的值為 : 2
a等于3;執行goto跳出!
不建議使用goto,容易造成代碼結構混亂
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/354691.html
標籤:其他
