面试题答案
一键面试package main
import "fmt"
func calculate(a, b int) int {
result := 0
// 定义错误处理标签
labelDivideByZero:
labelNegativeResult:
if b == 0 {
// 除零错误,跳转到除零错误处理标签
goto labelDivideByZero
}
result = a / b
if result < 0 {
// 结果为负数,跳转到负数结果处理标签
goto labelNegativeResult
}
return result
labelDivideByZero:
fmt.Println("除零错误")
return -1
labelNegativeResult:
fmt.Println("结果为负数")
return -2
}
你可以使用以下方式调用这个函数:
func main() {
res := calculate(10, 0)
fmt.Println("返回结果:", res)
res = calculate(10, -2)
fmt.Println("返回结果:", res)
res = calculate(10, 2)
fmt.Println("返回结果:", res)
}