透過向函式傳遞類來新增兩個複數的 Go 語言程式


在這篇文章中,我們將編寫一個 Go 語言程式,透過向函式傳遞類來新增兩個複數。我們將建立一個函式,該函式接受類及其屬性作為引數,並使用它輕鬆計算提供的複數之和。

演算法

  • 步驟 1 − 首先,我們需要匯入 fmt 包。

  • 步驟 2 − 然後,建立名為 Complex 的結構體,並在其中定義實部和虛部屬性。

  • 步驟 3 − 然後為上面宣告的 Complex 類建立一個名為 add() 的函式。此函式接受包含複數實部和虛部的 Complex 類,並以相同的格式返回最終結果。

  • 步驟 4 − 然後我們需要呼叫 main() 函式。在 main() 函式內部,宣告兩個複數併為其儲存值,然後在螢幕上列印這些複數。

  • 步驟 5 − 現在,呼叫在 Complex 類上定義的 add() 函式,並將兩個複數作為引數傳遞給它。

  • 步驟 6 − 將函式獲得的結果儲存在一個單獨的變數中。此變數包含加法的結果,並使用 fmt.Println() 函式在螢幕上列印它。

  • 步驟 7 − 現在,再舉一些例子,並重復這個過程,透過向函式傳遞類來找到兩個複數的和。

示例

在這個例子中,我們將編寫一個 Go 語言程式,透過向函式傳遞類來新增兩個複數。

package main
import (
   "fmt"
)
type Complex struct {
   real float64
   imag float64
}
func (c Complex) add(c2 Complex) Complex {
   return Complex{c.real + c2.real, c.imag + c2.imag}
}
func main() {
   //Example 1
   fmt.Println("Example 1")
   c1 := Complex{1.2, 3.4}
   fmt.Println("The first complex number is:", c1)
   c2 := Complex{5.6, 7.8}
   fmt.Println("The second complex number is:", c2)
   c3 := c1.add(c2)
   fmt.Printf("The complex number obtained by adding \n(%v + %vi) and (%v + %vi) is %v + %vi\n", c1.real, c1.imag, c2.real, c2.imag, c3.real, c3.imag)
   fmt.Println()
   
   //Example 2
   fmt.Println("Example 2")
   c7 := Complex{0.0, 0.0}
   fmt.Println("The first complex number is:", c7)
   c8 := Complex{3.3, 5.5}
   fmt.Println("The second complex number is:", c8)
   c9 := c7.add(c8)
   fmt.Printf("The complex number obtained by adding \n(%v + %vi) and (%v + %vi) is %v + %vi\n", c7.real, c7.imag, c8.real, c8.imag, c9.real, c9.imag)
}

輸出

Example 1
The first complex number is: {1.2 3.4}
The second complex number is: {5.6 7.8}
The complex number obtained by adding 
(1.2 + 3.4i) and (5.6 + 7.8i) is 6.8 + 11.2i

Example 2
The first complex number is: {0 0}
The second complex number is: {3.3 5.5}
The complex number obtained by adding 
(0 + 0i) and (3.3 + 5.5i) is 3.3 + 5.5i

結論

我們已經成功編譯並執行了一個 Go 語言程式,該程式透過向函式傳遞類來新增兩個複數,並附帶示例。該程式為一個類定義了一個函式,該函式接受兩個複數作為引數,並透過執行加法過程返回結果。

更新於:2023年2月16日

瀏覽量 133 次

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.