使用內建庫函式從虛部建立複數的Go語言程式
在本教程中,我們將學習如何在Go程式語言中從給定的虛部建立複數。
複數是Go語言的基本資料型別,它是實部和虛部的組合,在Go語言中,複數的實部和虛部都是浮點型。
複數 = 實數 + 虛數
Go程式語言中的`complex()`函式是一個內建函式,用於從兩個浮點值構造一個複數。
複數值的實部和虛部必須大小相同,返回值將是相應的複數型別。
實部和虛部的值是構造複數型別的引數。
示例:Go語言程式程式碼,在一個函式中從給定的虛部建立複數
語法
func complex(real, imaginary FloatType) ComplexType
演算法
步驟1 - 匯入`fmt`包
步驟2 - 開始`main()`函式。
步驟3 - 使用`Complex()`函式構造使用虛部的複數變數。
步驟4 - 使用建構函式初始化方法初始化變數
步驟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()`函式開始。
在下一行程式碼中,我們必須根據其給定的虛部建立複數。
接下來,使用建構函式初始化方法及其實部和虛數值初始化變數,並呼叫`Complex()`函式。
最後,使用內建函式`fmt.Println()`在螢幕上列印建立的複數。
結論
我們已經成功編譯並執行了Go語言程式碼示例,該示例演示瞭如何在Go程式語言中從給定的虛部建立複數。
在這個例子中,我們使用了內建函式`Complex()`來建立複數。
廣告