Swift程式列印複數的絕對值
在本文中,我們將學習如何編寫一個Swift程式來列印複數的絕對值。複數是以x+yi的形式表達的數,其中x和y是實數,'i'是虛數單位,也稱為iota。例如4+2i、6-4i等。複數的絕對值是實部和虛部平方和的正平方根。
$\mathrm{|\:絕對值\:|\:=\:\sqrt{(實部)^{2}\:+\:(虛部)^{2}}}$
例如:
複數 = 4 + 2i
$\mathrm{|\:絕對值\:|\:=\:\sqrt{(4)^{2}\:+\:(2)^{2}}}$
$\mathrm{=\:\sqrt{16 + 4}}$
$\mathrm{=\:\sqrt{20}}$
= 4.4721359549995
演算法
步驟1 - 建立一個結構體。
步驟2 - 建立兩個屬性來儲存實部和虛部。
步驟3 - 用於顯示覆數的方法。
步驟4 - 用於查詢給定複數絕對值的方法。
步驟5 - 建立並初始化ComplexNumber結構體的例項。
步驟6 - 使用點運算子訪問結構體的方法。
步驟7 - 列印輸出。
示例
以下是列印複數絕對值的Swift程式。
import Foundation
import Glibc
// Structure to create complex number
struct ComplexNumber{
var real: Double
var imaginary: Double
// Method to display complex number
func display(){
print("Complex number: \(real) + \(imaginary)i")
}
// Method to calculate absolute value of the // complex number
func absolute() -> Double {
return sqrt(real * real + imaginary * imaginary)
}
}
// Initialize complex number
let cNum = ComplexNumber(real: 5.0, imaginary: 6.0)
cNum.display()
print("Absolute Value:",cNum.absolute())
輸出
Complex number: 5.0 + 6.0i Absolute Value: 7.810249675906654
在上面的程式碼中,我們建立了一個結構體,它包含兩個屬性來儲存複數的實部和虛部,一個用於顯示覆數的方法,以及另一個用於查詢給定複數絕對值的方法。在absolute()函式中,我們使用sqrt()函式找到實部和虛部平方和的平方根。現在我們建立一個ComplexNumber結構體的例項並初始化複數。使用該例項和點運算子,我們訪問absolute()函式並顯示輸出。
結論
因此,這就是我們如何找到複數的絕對值。絕對值也稱為數到零的距離(線上性圖中),其值始終為正。
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP