Finish: 01-basic-functions - 基础函数
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func exercise1() int {
|
||||
fmt.Println("=== 练习1:无参数单返回值函数 ===")
|
||||
@@ -9,14 +12,11 @@ func exercise1() int {
|
||||
// 定义一个函数cube,接收一个int参数,返回其立方
|
||||
// 调用这两个函数并返回它们的和
|
||||
|
||||
____ func ____
|
||||
square := func(n int) ____ { return n * n }
|
||||
____
|
||||
}
|
||||
square := func(n int) 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) {
|
||||
@@ -25,19 +25,23 @@ func exercise2(a, b int) {
|
||||
// 定义一个函数,接收两个int参数a和b
|
||||
// 打印a + b, a - b, a * b
|
||||
// 格式: "加: 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 {
|
||||
fmt.Println("\n=== 练习3:可变参数 ===")
|
||||
|
||||
// 定义一个可变参数函数,计算所有数字的和
|
||||
sum := ____
|
||||
for _, num := range ____ {
|
||||
____
|
||||
sum := 0
|
||||
for _, num := range nums {
|
||||
sum += num
|
||||
}
|
||||
|
||||
return ____
|
||||
return sum
|
||||
}
|
||||
|
||||
func exercise4(name, city string) (string, string) {
|
||||
@@ -47,13 +51,13 @@ func exercise4(name, city string) (string, string) {
|
||||
// nameWithGreeting: 格式为 "Hello, {name}"
|
||||
// info: 格式为 "{name} lives in {city}"
|
||||
|
||||
var ____ string
|
||||
var ____
|
||||
var nameWithGreeting string
|
||||
var info string
|
||||
|
||||
nameWithGreeting = fmt.Sprintf("Hello, %s", name)
|
||||
info = fmt.Sprintf("%s lives in %s", name, city)
|
||||
|
||||
return ____, ____
|
||||
return nameWithGreeting, info
|
||||
}
|
||||
|
||||
func exercise5(name string) string {
|
||||
@@ -63,13 +67,13 @@ func exercise5(name string) string {
|
||||
// 返回大写的name
|
||||
// 提示:使用strings.ToUpper
|
||||
|
||||
____ := ____
|
||||
upperName := strings.ToUpper(name)
|
||||
|
||||
return ____
|
||||
return upperName
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println("=== 基础函数 练习 ===\n")
|
||||
fmt.Println("=== 基础函数 练习 ===")
|
||||
|
||||
result1 := exercise1()
|
||||
fmt.Printf("练习1结果: %d\n", result1)
|
||||
|
||||
Reference in New Issue
Block a user