Golang 使用内建的库函数来创建复数
在本教程中,我们将学习如何使用Go编程语言中给定的虚部创建复数。
复数是GoLang的基本数据类型,由实部和虚部组成,其中复数的两个部分都是浮点类型。
复数=实数+虚数
Go编程语言中的complex()函数是一个内建函数,用于从两个浮点数值构建复数。
复数的实部和虚部必须具有相同的类型,返回值将是相应的复数类型。
实部和虚部的值是构造复数类型的参数。
示例:使用一个单一函数从给定的虚部创建复数的Golang程序代码
语法
func complex(real, imaginary FloatType) ComplexType
步骤
- 步骤 1 :导入 fmt 包
-
步骤 2 :开始函数 main() 。
-
步骤 3 :使用虚部构建复数变量,使用 Complex() 。
-
步骤 4 :使用构造函数的 init 方法初始化变量。
-
步骤 5 :使用 fmt.Println() 在屏幕上打印复数。
示例
package main
// fmt package provides the function to print anything
import (
"fmt"
)
func main() {
fmt.Println("Golang Program to create Complex numbers from given imaginary parts")
// Constructing complex values
// initializing the variable using the constructor init
// using the function func complex(r, i FloatType) ComplexType
c1 := complex(7.25, 51.8)
c2 := complex(10, 20)
c3 := complex(-10.5, 20)
c4 := complex(1, -45.5)
c5 := complex(-11.45, 5)
// Printing the complex numbers from given imaginary parts
fmt.Println("The complex number of c1 is", c1)
fmt.Println("The complex number of c2 is", c2)
fmt.Println("The complex number of c3 is", c3)
fmt.Println("The complex number of c4 is", c4)
fmt.Println("The complex number of c15 is", c5)
}
输出
Golang Program to create Complex numbers from given imaginary parts
The complex number of c1 is (7.25+51.8i)
The complex number of c2 is (10+20i)
The complex number of c3 is (-10.5+20i)
The complex number of c4 is (1-45.5i)
The complex number of c15 is (-11.45+5i)
代码描述
-
在上面的程序中,我们首先声明了main包。
-
我们导入了包含fmt函数的fmt包的文件。
-
我们开始main()函数。Go程序的执行从 函数main() 开始。
-
在下一行代码中,我们需要根据给定的虚部创建复数。
-
接下来,使用构造函数init方法初始化变量,并调用 Complex() 函数。
-
最后,使用内置函数 fmt.Println() 在屏幕上打印创建的复数。
结论
我们成功地编译并执行了一个示例,展示了如何在Go编程语言中根据给定的虚部创建复数。
在这个示例中,我们使用了内置函数Complex()来创建复数。