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