我正在注册一个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"];
答案 0 :(得分:2)
DDMathParser作者在这里。
有两件事是错的,有一件是不理想的。
"2x"
。这很好,除了x
被解释为函数,但在你的for循环中你正在将x
视为变量。您需要从根本上改变函数的工作方式,或使用表单2 * $x
(或仅2$x
)作为函数的第一个参数。doubleValue
,而是取而代之的是integerValue
并避免整个double-to int转换。以下是我如何清理你的功能(尽管你应该多做一些填写error
输出参数的方法):
[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];
//get the start and end values
NSInteger startValue = [[eval evaluateExpression:start withSubstitutions:vars error:error] integerValue];
NSInteger endValue = [[eval evaluateExpression:end withSubstitutions:vars error:error] integerValue];
double sum = 0;
for (NSInteger i = startValue; i <= endValue; i++) {
NSDictionary *substitution = @{@"x": @(i)};
NSNumber *value = [eval evaluateExpression:expr withSubstitutions:substitution error:error];
sum += [value doubleValue];
}
final = [DDExpression numberExpressionWithNumber:@(sum)];
}
return final;
} forName:@"sum2"];
有了这个,你可以sum2(2*$x, 2, 4)
,它将评估为18。