通过将类传递给函数来添加两个复数的 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")
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
Result: 8.0 + 10.0i
结论
因此,这就是我们如何通过将类传递给函数来添加两个复数。在复数的加法中,我们将实部与实部相加,虚部与虚部相加。我们不允许将实部与虚部相加。
广告