如何解决Golang return 或 float 或 complex
我正在尝试编写三次方程求解器。
func (a,b,c,d float64) (returnType,err){
if a<0{
return complex,nil
}
if a>=0 {
return float64,nil
}
}
有没有办法返回和接口或其他东西来管理这种行为?
解决方法
由于实数(浮点数)是复数的一个子集,您可以选择始终返回一个复数,而在您只返回 float64
的地方,您留下虚部 0
:
func abcd(a,b,c,d float64) (complex128,error) {
if a < 0 {
r,j := 1.0,2.0
return complex(r,j),nil
}
if a >= 0 {
r := 3.0
return complex(r,0),nil
}
return 0 + 0i,nil
}
测试:
c,err := abcd(1,0)
fmt.Println(c,err)
if imag(c) == 0 {
fmt.Println("\treal:",real(c))
}
c,err = abcd(-1,real(c))
}
哪些输出(在 Go Playground 上试试):
(3+0i) <nil>
real: 3
(1+2i) <nil>
是的,如果将返回一个复数,其虚部为 0
,则您无法将这种特殊情况与仅返回实数的情况区分开来。也许你不必?如果没有,这不是问题。如果您确实需要区分它们,您还可以返回第三个值,告知结果是否实际上是一个复数:
func abcd(a,d float64) (x complex128,isComplex bool,err error) {
if a < 0 {
r,true,false,isC,err)
if !isC {
fmt.Println("\treal:",real(c))
}
输出是一样的。在 Go Playground 上试试这个。
上述解决方案是可能的,因为实数是复数的子集。在一般情况下,您可以使用多个返回值,每个返回值都是一个指针,您可以检查哪个返回值不是 nil
。像这样:
func abcd(a,d float64) (*complex128,*float64,2.0
x = :complex(r,j)
return &x,nil,nil
}
if a >= 0 {
f := 3.0
return nil,&f,nil
}
return nil,f,err)
if c != nil {
fmt.Println("\tcmplx:",*c)
}
if f != nil {
fmt.Println("\treal:",*f)
}
c,*f)
}
输出(在 Go Playground 上尝试):
<nil> 0xc000018050 <nil>
real: 3
0xc000018070 <nil> <nil>
cmplx: (1+2i)
您也可以结合最后两种解决方案:您可以返回非指针和一个 isComplex
标志,告诉哪个返回值是有效的。
使用空接口interface{}
作为返回类型来处理不同类型的返回值。
使用类型开关来判断返回值的类型并进行适当的处理。
package main
import (
"fmt"
)
func abcd(a,d float64) (interface{},error) {
if a < 0 {
return complex(0,nil
}
if a >= 0 {
return float64(0),nil
}
func main() {
r,_ := abcd(0,1,2,3)
fmt.Printf("%T %v\n",r,r)
switch x := r.(type) {
case complex64:
fmt.Printf("%T %v\n",x,x)
case complex128:
fmt.Printf("%T %v\n",x)
case float32:
fmt.Printf("%T %v\n",x)
case float64:
fmt.Printf("%T %v\n",x)
}
r,_ = abcd(-1,x)
}
}
//Output:
//float64 0
//float64 0
//complex128 (0+0i)
//complex128 (0+0i)
也读
,复虚数系统示例
func main() {
complex1 := complex(10,4)
complex2 := 1 + 4i
fmt.Println("complex Number 1",complex1)
fmt.Println("complex Number 2:",complex2)
fmt.Println("Real Number 1:",real(complex1))
fmt.Println("Imaginary Number 1:",imag(complex1))
fmt.Println("Real Number 1:",real(complex2))
fmt.Println("Imaginary Number 2:",imag(complex2))
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。