我注册求和函数即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"];