Golang 查找指定复数的绝对值
Go语言提供了cmplx包的基本常量和复数的数学函数的内置支持。您可以使用math / cmplx包提供的Abs()函数来查找指定复数的绝对值。因此,您需要在程序中添加一个math / cmplx包,并使用import关键字来访问Abs()函数。
语法:
func Abs(a complex128) float64
让我们通过以下示例来讨论这个概念:
示例1:
// Golang program to illustrate
// how to find absolute value
package main
import (
"fmt"
"math/cmplx"
)
// Main function
func main() {
// Finding absolute value of
// the specified complex number
// Using Abs() function
res_1 := cmplx.Abs(3 + 5i)
res_2 := cmplx.Abs(-4 + 8i)
res_3 := cmplx.Abs(-8 - 7i)
// Displaying the result
fmt.Println("Random Number 1:", res_1)
fmt.Println("Random Number 2: ", res_2)
fmt.Println("Random Number 3: ", res_3)
}
输出:
Random Number 1: 5.8309518948453
Random Number 2: 8.94427190999916
Random Number 3: 10.63014581273465
示例2:
// Golang program to illustrate how
// to find absolute value
package main
import (
"fmt"
"math/cmplx"
)
// Main function
func main() {
// Complex numbers
cnumber_1 := complex(5, 7)
cnumber_2 := complex(6, 9)
// Finding absolute values
absvalue_1 := cmplx.Abs(cnumber_1)
absvalue_2 := cmplx.Abs(cnumber_2)
// Sum of two absolute values
res := absvalue_1 + absvalue_2
// Displaying results
fmt.Println("Complex Number 1: ", cnumber_1)
fmt.Println("Complex Number 2: ", cnumber_2)
fmt.Println("Sum of the absolute values of " +
"the given complex numbers: ")
fmt.Printf("%.1f + %.1f = %.1f", absvalue_1, absvalue_2, res)
}
输出:
Complex Number 1: (5+7i)
Complex Number 2: (6+9i)
Sum of the absolute values of the given complex numbers:
8.6 + 10.8 = 19.4