本文共 2385 字,大约阅读时间需要 7 分钟。
在软件开发中,复数运算是一个常见需求。Objective-C作为一门灵活强大的编程语言,拥有丰富的类和方法,能够轻松支持复数运算。以下是一个简洁的Objective-C实现复数类的代码示例,支持加法、减法、乘法、除法和取模运算。
#import@interface Complex : NSObject { double _real; double _imaginary;}@property (nonatomic, assign) double real;@property (nonatomic, assign) double imaginary;@end
@interface Complex : NSObject { double _real; double _imaginary;}@property (nonatomic, assign) double real;@property (nonatomic, assign) double imaginary;@end -(id)initWithReal:(double)real withImaginary:(double)imaginary { self.real = real; self.imaginary = imaginary; return self;} -(Complex *)add:(Complex *)other { Complex *result = [[Complex alloc] init]; result.real = self.real + other.real; result.imaginary = self.imaginary + other.imaginary; return result;} -(Complex *)subtract:(Complex *)other { Complex *result = [[Complex alloc] init]; result.real = self.real - other.real; result.imaginary = self.imaginary - other.imaginary; return result;} -(Complex *)multiply:(Complex *)other { Complex *result = [[Complex alloc] init]; result.real = self.real * other.real - self.imaginary * other.imaginary; result.imaginary = self.real * other.imaginary + self.imaginary * other.real; return result;} -(Complex *)divide:(Complex *)other { Complex *result = [[Complex alloc] init]; double divisor = other.real * other.real + other.imaginary * other.imaginary; if (divisor != 0) { result.real = (self.real * other.real + self.imaginary * other.imaginary) / divisor; result.imaginary = (self.imaginary * other.real - self.real * other.imaginary) / divisor; } else { result.real = 0; result.imaginary = 0; } return result;} -(Complex *)modulo:(Complex *)other { Complex *result = [[Complex alloc] init]; double divisor = other.real * other.real + other.imaginary * other.imaginary; if (divisor != 0) { result.real = (self.real * other.real + self.imaginary * other.imaginary) / divisor; result.imaginary = (self.imaginary * other.real - self.real * other.imaginary) / divisor; } else { result.real = 0; result.imaginary = 0; } return result;} 这个复数类实现了基本的复数运算,适用于需要处理复数的场景,如工程力学、电路设计、科学计算等。代码结构清晰,方法简洁,易于扩展和维护。
如果需要更高级的功能,如复数的共轭、极坐标形式转换等,可以根据实际需求进行扩展。
转载地址:http://hvifk.baihongyu.com/