📜  在 Golang 中查找指定复数的绝对值?

📅  最后修改于: 2021-10-24 13:04:05             🧑  作者: Mango

Go 语言在 cmplx 包的帮助下为复数的基本常量和数学函数提供了内置支持。您可以借助math/cmplx 包提供的Abs()函数找到指定复数的绝对值。因此,您需要借助 import 关键字在程序中添加一个 math/cmplx 包来访问 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