Golang 如何添加两个复数

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 的信息,您可以探索这个教程。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程