如何将浮点数转换为复数?

使用非常简单的代码:


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

我尝试了不同的方法,但找不到如何将 a 转换float64为complex128(只是为了能够对cmplx.Sqrt()负数使用函数)。


处理这个问题的正确方法是什么?


紫衣仙女
浏览 194回答 1
1回答

互换的青春

您并不是真的想将 a 转换为float64,complex128而是想构造一个complex128指定实部的值。为此可以使用内置complex()函数:func complex(r, i FloatType) ComplexType使用它你的sqrt()功能:func sqrt(x float64) string {&nbsp; &nbsp; if x < 0 {&nbsp; &nbsp; &nbsp; &nbsp; return fmt.Sprint(cmplx.Sqrt(complex(x, 0)))&nbsp; &nbsp; }&nbsp; &nbsp; return fmt.Sprint(math.Sqrt(x))}在Go Playground上试一试。笔记:您可以在float不使用复数的情况下计算负数的平方根:它将是一个复数值,其实部为0虚部math.Sqrt(-x)i(因此结果:)(0+math.Sqrt(-x)i):func sqrt2(x float64) string {&nbsp; &nbsp; if x < 0 {&nbsp; &nbsp; &nbsp; &nbsp; return fmt.Sprintf("(0+%.15fi)", math.Sqrt(-x))&nbsp; &nbsp; }&nbsp; &nbsp; return fmt.Sprint(math.Sqrt(x))}
打开App,查看更多内容
随时随地看视频慕课网APP