透過將類傳遞給函式來新增兩個複數的 Swift 程式
在 Swift 中,複數是實數和虛數的組合。因此,我們建立一個類來儲存複數的實部和虛部,然後我們將此類傳遞給函式以找到兩個複數的和。
演算法
步驟 1 - 建立一個類來儲存複數的實部和虛部。
步驟 2 - 建立一個名為“add”的函式,該函式將兩個類物件作為引數,並透過新增兩個複數的實部和虛部來返回這兩個複數的和。
步驟 3 - 現在建立類的兩個例項,並將它們傳遞給“add”函式以找到總和。
步驟 4 - 列印輸出。
示例
在這個例子中,我們將首先建立一個名為“MyComplexNumber”的類,它有兩個屬性 real 和 imaginary 來儲存複數的實部和虛部。它還有一個初始化器來設定 real 和 imaginary 屬性的初始值。然後我們建立一個名為 add() 的函式,它將兩個“MyComplexNumber”的物件作為引數並找到複數的和。為了顯示最終結果,我們建立了兩個“MyComplexNumber”的例項並將它們傳遞給“add”函式。
import Foundation
import Glibc
// Creating a class to store complex number
class MyComplexNumber {
var real: Double
var imaginary: Double
init(real: Double, imaginary: Double) {
self.real = real
self.imaginary = imaginary
}
}
// Function to add two complex numbers
func add(_ num1: MyComplexNumber, _ num2: MyComplexNumber) -> MyComplexNumber {
let realNum = num1.real + num2.real
let imaginaryNum = num1.imaginary + num2.imaginary
return MyComplexNumber(real: realNum, imaginary: imaginaryNum)
}
// Creating instance of the class
let obj1 = MyComplexNumber(real: 3.0, imaginary: 4.0)
let obj2 = MyComplexNumber(real: 5.0, imaginary: 6.0)
let result = add(obj1, obj2)
print("Result: \(result.real) + \(result.imaginary)i")
輸出
Result: 8.0 + 10.0i
結論
因此,這就是我們如何透過將類傳遞給函式來新增兩個複數。在複數的加法中,我們將實部與實部相加,虛部與虛部相加。我們不允許將實部與虛部相加。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP