1 回答

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
您并不是真的想將 a 轉(zhuǎn)換為float64,complex128而是想構(gòu)造一個(gè)complex128指定實(shí)部的值。
為此可以使用內(nèi)置complex()函數(shù):
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不使用復(fù)數(shù)的情況下計(jì)算負(fù)數(shù)的平方根:它將是一個(gè)復(fù)數(shù)值,其實(shí)部為0虛部math.Sqrt(-x)i(因此結(jié)果:)(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))
}
- 1 回答
- 0 關(guān)注
- 246 瀏覽
添加回答
舉報(bào)