Go language entry classic - function exercises

1. In Go language, how many values ​​can a function return?

Answer: Unlimited values ​​can be returned, and multiple return value types can be different.

package main

import "fmt"

func main() {
	i, j := test()
	fmt.Println(i, j)
	fmt.Println(test())
}

func test() (string, int) {
	i := "Hello"
	j := 5
	return i, j
}

2. What is the function that calls itself called?

Answer: recursive function

package main

import "fmt"

func main() {
	test(1, 0)
}

func test(portion int, eaten int) int {
	eaten += portion
	if eaten >= 5 {
		fmt.Printf("I'm full! I've eaten %d fishes!\n", eaten)
		return eaten
	}
	fmt.Printf("I'm still hungry! I've eaten %d fishes!\n", eaten)
	return test(portion, eaten)
}

3. In Go language, can functions be passed as parameters to other functions?

Answer: Yes! Functions themselves can be used as data types.

package main

import (
	"fmt"
)

func main() {
	fn := func() string {
		return "Function Called"
	}
	fmt.Println(test(fn))
}

func test(f func() string) string {
	return f()
}

4. Write a function to convert Fahrenheit to Celsius. What are the input and output of this function?

//华氏温度 :摄氏温度 = 1 :17.22

package main

import "fmt"

func main() {
	var c float64
	fmt.Println("请输入华氏温度:")
	fmt.Scanf("%f", &c)
	fmt.Printf("华氏温度 %f 转化为 摄氏温度 %f\n", c, ftoc(c))
}

func ftoc(f float64) float64 {
	ret := f * 17.22
	return ret
}

5. Write a function that calls itself 10 times before exiting.

// 递归调用10次

package main

import "fmt"

func main() {
	s := recursion(1, 0)
	fmt.Println(s)
}

func recursion(t int, ret int) int {
	ret += t
	if ret >= 10 {
		return ret
	}
	return recursion(t, ret)
}

6. Write a function that takes 2 parameters and returns 3 values

// 函数接受2个参数,返回3个值

package main

import "fmt"

func main() {
	fmt.Println(test(1, 2))
}

func test(i int, j int) (int, int, int) {
	return 1, 2, 3
}

Guess you like

Origin blog.csdn.net/fengqy1996/article/details/124216963