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)
}
在上面的代码中,我们首先声明复数,然后使用复数init语法初始化其中两个复数的实值和虚值。之后,我们将这两个复数相加,并将结果存储在第三个变量中,然后打印出来。
输出
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)
这是对复数进行初始化,然后进行加法的两种方法。