Golang 通过将类传递给函数添加两个复数
在本文中,我们将编写一个Go语言程序,通过将类传递给函数来添加两个复数。在这里,我们将创建一个函数给予类作为参数,以及它的属性,我们可以使用它来轻松计算所提供的复数的和。
步骤
- 步骤1 - 首先,我们需要导入fmt包。
-
步骤2 - 然后,创建一个名为Complex的结构体,并在其中定义实数和虚数的属性。
-
步骤3 - 然后创建一个名为add()的函数,该函数接受上述声明的Complex类,并返回相同格式的最终结果,
-
步骤4 - 然后我们需要调用main()函数。在main()内部声明两个复数,并将值存储到它们中,并在屏幕上打印这些复数。
-
步骤5 - 现在,调用在复数类上定义的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语言程序,通过将一个类传递给一个函数来实现两个复数的相加,并给出了示例。该程序定义了一个接受两个复数作为参数并执行加法运算的类的函数,并返回结果。