With the very simple code :
package main
import (
"fmt"
"math"
"math/cmplx"
)
func sqrt(x float64) string {
if x < 0 {
return fmt.Sprint(cmplx.Sqrt(complex128(x)))
}
return fmt.Sprint(math.Sqrt(x))
}
func main() {
fmt.Println(sqrt(2), sqrt(-4))
}
我收到以下错误信息:
main.go:11: cannot convert x (type float64) to type complex128
我尝试了不同的方法,但无法找到将
float64
转换为 complex128
的方法(只是为了能够在负数上使用 cmplx.Sqrt()
函数)。正确的处理方式是什么?