通过向函数传递类来添加两个复数的 Go 语言程序


在这篇文章中,我们将编写一个 Go 语言程序,通过向函数传递类来添加两个复数。我们将创建一个函数,该函数接受类及其属性作为参数,并使用它轻松计算提供的复数之和。

算法

  • 步骤 1 − 首先,我们需要导入 fmt 包。

  • 步骤 2 − 然后,创建名为 Complex 的结构体,并在其中定义实部和虚部属性。

  • 步骤 3 − 然后为上面声明的 Complex 类创建一个名为 add() 的函数。此函数接受包含复数实部和虚部的 Complex 类,并以相同的格式返回最终结果。

  • 步骤 4 − 然后我们需要调用 main() 函数。在 main() 函数内部,声明两个复数并为其存储值,然后在屏幕上打印这些复数。

  • 步骤 5 − 现在,调用在 Complex 类上定义的 add() 函数,并将两个复数作为参数传递给它。

  • 步骤 6 − 将函数获得的结果存储在一个单独的变量中。此变量包含加法的结果,并使用 fmt.Println() 函数在屏幕上打印它。

  • 步骤 7 − 现在,再举一些例子,并重复这个过程,通过向函数传递类来找到两个复数的和。

示例

在这个例子中,我们将编写一个 Go 语言程序,通过向函数传递类来添加两个复数。

Open Compiler
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) }

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

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 次

开启你的职业生涯

通过完成课程获得认证

开始学习
广告