本文共 1241 字,大约阅读时间需要 4 分钟。
Polynomial类Objective-C实现多项式算法示例
Polynomial.h文件:
#import@interface Polynomial : NSObject@property (nonatomic, strong) NSMutableArray *coefficients;@end
Polynomial.m文件:
@implementation Polynomial- (id)init { self = [NSObject new]; self.coefficients = [NSMutableArray new]; return self;}- (void)addTerm:(double)term { [self.coefficients addObject:term];}- (void)removeTerm:(double)term { [self.coefficients removeObject:term];}- (void)multiplyByPolynomial:(Polynomial *)anotherPolynomial { NSMutableArray *newCoefficients = [NSMutableArray new]; for (double coefficient : self.coefficients) { for (double anotherCoefficient : anotherPolynomial.coefficients) { [newCoefficients addObject:coefficient * anotherCoefficient]; } } self.coefficients = newCoefficients;}- (double)evaluateAtX:(double)x { double result = 0.0; for (double coefficient : self.coefficients) { result += coefficient * pow(x, [self.degree]); [self.coefficients removeObject:0.0]; // 移除零项 } return result;}- (int)degree { return [self.coefficients count] - 1;} Polynomial类实现了多项式的基本操作,包括:
通过这种方式,我们可以创建一个多项式对象,并通过上述方法进行操作。这个实现简化了多项式运算,使其易于使用和扩展。
转载地址:http://benfk.baihongyu.com/