我正在注册一个求和函数,即sum(expression,initial,final)
. 包含自expression
变量x
,initial
和final
是整数。例如,sum(2x,2,4)
应该返回 2*2+3*2+4*2= 18
。但是,我在替换和之间x
的expression
每个值时遇到了麻烦。这是我的代码,它不起作用。谁能告诉我如何解决它?initial
final
//sum(expr (dependent on x),initial,final)
[evaluator registerFunction:^DDExpression *(NSArray *args, NSDictionary *vars, DDMathEvaluator *eval, NSError *__autoreleasing *error) {
DDExpression *final = nil;
if([args count] == 3){
DDExpression *expr = [args objectAtIndex:0];
DDExpression *start = [args objectAtIndex:1];
DDExpression *end = [args objectAtIndex:2];
//test whether start and end are integers
double startDouble = [[start evaluateWithSubstitutions:nil evaluator:evaluator error:nil] doubleValue];
double endDouble = [[end evaluateWithSubstitutions:nil evaluator:evaluator error:nil] doubleValue];
int startInt = (int)startDouble;
int endInt = (int)endDouble;
if (((startDouble-startInt)>0.9999 || (startDouble-startInt)<0.0001) && ((endDouble-endInt)>0.9999 || (endDouble-endInt)<0.0001)) {
//start and end are integers
double resultSum = 0;
for (int i=startInt; i<=endInt; i++) {
NSNumber *xValue = [NSNumber numberWithInt:i];
NSDictionary *substitution = [NSDictionary dictionaryWithObjectsAndKeys:xValue,@"x", nil];
NSNumber *valueOfExpr = [expr evaluateWithSubstitutions:substitution evaluator:evaluator error:nil];
resultSum = resultSum + [valueOfExpr doubleValue];
}
final = [DDExpression numberExpressionWithNumber:[NSNumber numberWithDouble:resultSum]];
}
}
return final;
}forName:@"sum"];