如何在 Golang 中新增兩個複數?
在本教程中,我們將學習如何在 Golang 中宣告和新增複數。複數是由實部和虛部組成的數,這使得它們與其他型別的數有所不同。Golang 支援聲明覆數型別的變數。
複數 = 實數 + 虛數
在 Golang 中宣告和初始化複數以及稍後新增它們的不同方法.
使用複數初始化語法進行初始化
語法
var variableName complex64 var variableName complex128 variableName = (realValue) + (imaginaryValue)i
演算法
步驟 1 − 定義我們要新增的複數變數以及我們將儲存結果的複數變數。
步驟 2 − 使用要新增的相應值初始化變數。
步驟 3 − 將兩個數相加並將結果儲存在第三個變數中。
步驟 4 − 列印新增兩個複數後的結果。
示例
package main // fmt package provides the function to print anything import "fmt" func main() { // declaring the complex number using the var keyword var complexNumber1, complexNumber2, complexNumber3 complex64 // initializing the variable using complex number init syntax complexNumber1 = 3 + 3i complexNumber2 = 2 + 5i fmt.Println("The First Complex Number is", complexNumber1) fmt.Println("The Second Complex Number is", complexNumber2) // adding the complex numbers using + operator complexNumber3 = complexNumber1 + complexNumber2 fmt.Println("Printing the addition of two complex numbers by initializing the variable using complex number init syntax.") // printing the complex number after addition fmt.Println(complexNumber1, "+", complexNumber2, "=", complexNumber3) }
在上面的程式碼中,我們首先聲明覆數,然後使用複數初始化語法及其實部和虛部值初始化其中的兩個。之後,我們將這兩個複數相加並將結果儲存在第三個變數中,然後列印它。
輸出
The First Complex Number is (3+3i) The Second Complex Number is (2+5i) Printing the addition of two complex numbers by initializing the variable using complex number init syntax. (3+3i) + (2+5i) = (5+8i)
使用建構函式進行初始化
透過這種方式,我們使用建構函式來初始化複數變數,您只需傳遞實部和虛部值即可。
語法
var variableName complex64 var variableName complex128 variableName = complex(realValue, imaginaryValue)
示例
package main // fmt package provides the function to print anything import "fmt" func main() { // declaring the complex number using the var keyword var complexNumber1, complexNumber2, complexNumber3 complex64 // initializing the variable using the constructor complexNumber1 = complex(5, 4) complexNumber2 = complex(6, 3) fmt.Println("The First Complex Number is", complexNumber1) fmt.Println("The Second Complex Number is", complexNumber2) // adding the complex numbers using + operator complexNumber3 = complexNumber1 + complexNumber2 fmt.Println("Printing the addition of two complex numbers by initializing the variable using the constructor.") // printing the complex number after addition fmt.Println(complexNumber1, "+", complexNumber2, "=", complexNumber3) }
在上面的程式碼中,我們首先聲明覆數,然後使用建構函式及其實部和虛部值初始化其中的兩個。之後,我們將這兩個複數相加並將結果儲存在第三個變數中,然後列印它。
輸出
The First Complex Number is (5+4i) The Second Complex Number is (6+3i) Printing the addition of two complex numbers by initializing the variable using the constructor. (5+4i) + (6+3i) = (11+7i)
以上是初始化複數並將其相加的兩種方法。要了解更多關於 Golang 的資訊,您可以瀏覽此 教程。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP