Finish: 03-for-loop - for循环

This commit is contained in:
2026-03-17 15:24:34 +08:00
parent 50306fbe17
commit e6db364f3e
+11 -13
View File
@@ -2,7 +2,7 @@ package main
import "fmt" import "fmt"
func exercise1() int { func exercise1() {
fmt.Println("=== 练习1:基本for循环 ===") fmt.Println("=== 练习1:基本for循环 ===")
sum := 0 sum := 0
@@ -11,15 +11,14 @@ func exercise1() int {
// 初始化: i := 1 // 初始化: i := 1
// 条件: i <= 10 // 条件: i <= 10
// 后置: i++ // 后置: i++
for ____; ____; ____ { for i := 1; i <= 10; i++ {
sum += i sum += i
} }
fmt.Printf("1到10的和: %d\n", sum) fmt.Printf("1到10的和: %d\n", sum)
return sum
} }
func exercise2() int { func exercise2() {
fmt.Println("\n=== 练习2:while形式的for循环 ===") fmt.Println("\n=== 练习2:while形式的for循环 ===")
sum := 0 sum := 0
@@ -27,13 +26,12 @@ func exercise2() int {
// 使用while形式的for循环,计算1到5的乘积 // 使用while形式的for循环,计算1到5的乘积
// 提示:省略初始化和后置语句 // 提示:省略初始化和后置语句
for ____ { for i <= 5 {
sum *= i sum *= i
i++ i++
} }
fmt.Printf("1到5的乘积: %d\n", sum) fmt.Printf("1到5的乘积: %d\n", sum)
return sum
} }
func exercise3() []int { func exercise3() []int {
@@ -46,12 +44,12 @@ func exercise3() []int {
// 如果数字大于8,停止循环(使用break) // 如果数字大于8,停止循环(使用break)
i := 1 i := 1
for i <= 10 { for i <= 10 {
if ____ { if i%3 == 0 {
i++ i++
____ continue
} }
if ____ { if i > 8 {
____ break
} }
nums = append(nums, i) nums = append(nums, i)
i++ i++
@@ -69,7 +67,7 @@ func exercise4() string {
// 使用for-range遍历切片,格式化输出 // 使用for-range遍历切片,格式化输出
// 提示:range会返回索引和值,示例: "0: 苹果" // 提示:range会返回索引和值,示例: "0: 苹果"
for ____, ____ := range ____ { for index, value := range fruits {
result += fmt.Sprintf("%d: %s ", index, value) result += fmt.Sprintf("%d: %s ", index, value)
} }
@@ -85,7 +83,7 @@ func exercise5() string {
// 使用for-range遍历map,格式化输出 // 使用for-range遍历map,格式化输出
// 提示:range遍历map时,返回的是键和值 // 提示:range遍历map时,返回的是键和值
for ____, ____ := range ____ { for name, score := range scores {
result += fmt.Sprintf("%s: %d ", name, score) result += fmt.Sprintf("%s: %d ", name, score)
} }
@@ -94,7 +92,7 @@ func exercise5() string {
} }
func main() { func main() {
fmt.Println("=== for循环 练习 ===\n") fmt.Println("=== for循环 练习 ===")
exercise1() exercise1()
exercise2() exercise2()