Golang程序 使用内置库函数从给定的虚部创建复数
在本教程中,我们将学习如何在Go编程语言中从给定的虚数部分创建复数。
复数是GoLang语言的一种基本数据类型,是实部和虚部的组合,复数的两部分在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() 将创建的复数打印到屏幕上 。
总结
我们已经成功地编译并执行了Golang代码的例子,即如何用Go编程语言从给定的虚数部分创建复数。
在这个例子中,我们使用了一个内置的函数Complex()来创建复数。