使用非常简单的代码:
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()
负数函数)。
处理这个问题的正确方法是什么?
最佳答案
您并不是真的想将 float64
转换为 complex128
,而是想构造一个 complex128
值,您可以在其中指定实数部分。
为此可以使用内置的 complex()
功能:
func complex(r, i FloatType) ComplexType
使用你的 sqrt()
函数:
func sqrt(x float64) string {
if x < 0 {
return fmt.Sprint(cmplx.Sqrt(complex(x, 0)))
}
return fmt.Sprint(math.Sqrt(x))
}
在 Go Playground 上试试.
注意:
您可以在不使用复数的情况下计算负数 float
的平方根:它将是一个复数,其实部为 0
,虚部为 math.Sqrt(-x)i
(所以结果:(0+math.Sqrt(-x)i)
):
func sqrt2(x float64) string {
if x < 0 {
return fmt.Sprintf("(0+%.15fi)", math.Sqrt(-x))
}
return fmt.Sprint(math.Sqrt(x))
}
关于go - 如何将 float 转换为复数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31022456/