Finish: 01-basic-functions - 基础函数

This commit is contained in:
2026-03-17 15:46:46 +08:00
parent 787dd02bb3
commit d570ed6810
+22 -18
View File
@@ -1,6 +1,9 @@
package main package main
import "fmt" import (
"fmt"
"strings"
)
func exercise1() int { func exercise1() int {
fmt.Println("=== 练习1:无参数单返回值函数 ===") fmt.Println("=== 练习1:无参数单返回值函数 ===")
@@ -9,14 +12,11 @@ func exercise1() int {
// 定义一个函数cube,接收一个int参数,返回其立方 // 定义一个函数cube,接收一个int参数,返回其立方
// 调用这两个函数并返回它们的和 // 调用这两个函数并返回它们的和
____ func ____ square := func(n int) int { return n * n }
square := func(n int) ____ { return n * n }
____
}
cube := func(n int) ____ { ____ } cube := func(n int) int { return n * n * n }
return ____(3) + ____(2) return square(3) + cube(2)
} }
func exercise2(a, b int) { func exercise2(a, b int) {
@@ -25,19 +25,23 @@ func exercise2(a, b int) {
// 定义一个函数,接收两个int参数a和b // 定义一个函数,接收两个int参数a和b
// 打印a + b, a - b, a * b // 打印a + b, a - b, a * b
// 格式: "加: 5, 减: 1, 乘: 6" // 格式: "加: 5, 减: 1, 乘: 6"
fmt.Printf("加: %d, 减: %d, 乘: %d\n", ____, ____, ____) sum := a + b
difference := a - b
product := a * b
fmt.Printf("加: %d, 减: %d, 乘: %d\n", sum, difference, product)
} }
func exercise3(nums ...int) int { func exercise3(nums ...int) int {
fmt.Println("\n=== 练习3:可变参数 ===") fmt.Println("\n=== 练习3:可变参数 ===")
// 定义一个可变参数函数,计算所有数字的和 // 定义一个可变参数函数,计算所有数字的和
sum := ____ sum := 0
for _, num := range ____ { for _, num := range nums {
____ sum += num
} }
return ____ return sum
} }
func exercise4(name, city string) (string, string) { func exercise4(name, city string) (string, string) {
@@ -47,13 +51,13 @@ func exercise4(name, city string) (string, string) {
// nameWithGreeting: 格式为 "Hello, {name}" // nameWithGreeting: 格式为 "Hello, {name}"
// info: 格式为 "{name} lives in {city}" // info: 格式为 "{name} lives in {city}"
var ____ string var nameWithGreeting string
var ____ var info string
nameWithGreeting = fmt.Sprintf("Hello, %s", name) nameWithGreeting = fmt.Sprintf("Hello, %s", name)
info = fmt.Sprintf("%s lives in %s", name, city) info = fmt.Sprintf("%s lives in %s", name, city)
return ____, ____ return nameWithGreeting, info
} }
func exercise5(name string) string { func exercise5(name string) string {
@@ -63,13 +67,13 @@ func exercise5(name string) string {
// 返回大写的name // 返回大写的name
// 提示:使用strings.ToUpper // 提示:使用strings.ToUpper
____ := ____ upperName := strings.ToUpper(name)
return ____ return upperName
} }
func main() { func main() {
fmt.Println("=== 基础函数 练习 ===\n") fmt.Println("=== 基础函数 练习 ===")
result1 := exercise1() result1 := exercise1()
fmt.Printf("练习1结果: %d\n", result1) fmt.Printf("练习1结果: %d\n", result1)