我註冊的求和功能是sum(expression,initial,final)
。 expression
包含自變量x
和initial
和final
是整數。例如,sum(2x,2,4)
應返回2 * 2 + 3 * 2 + 4 * 2 = 18
。但是,我無法在expression
中替換x
中的每個值initial
和final
之間的值。這是我的代碼,它不起作用。任何人都可以告訴我如何解決它?任何人都可以幫助解決這個DDMathParser新功能嗎?
//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"];
爲什麼不直接向戴夫德隆自己提問? :) –