增加对不合法函数操作数时返回结果的处理,增加对中间结果的value值应用

This commit is contained in:
zhangkun 2018-05-30 11:43:45 +08:00
parent 918816a607
commit 84f9e126ae
3 changed files with 12 additions and 2 deletions

View file

@ -44,7 +44,11 @@ class Calculator
if(array_key_exists($variable, $variables)) {
$value = $variables[$variable];
} elseif (array_key_exists($variable, $midresults)) { //增加对中间结果的递归计算
$value = $oExecutor->execute($midresults[$variable]['formula']);
if(isset($midresults[$variable]['value'])) { //增加对中间结果的使用
$value = $midresults[$variable]['value'];
} else {
$value = $oExecutor->execute($midresults[$variable]['formula']);
}
} else {
throw new UnknownVariableException();
}

View file

@ -35,6 +35,9 @@ class TokenFunction extends AbstractContainerToken implements InterfaceFunction
array_push($args, array_pop($stack)->getValue());
}
$result = call_user_func_array($function, $args);
if(is_nan($result)) { //增加把不合法计算表达式的值置0
$result = 0.0;
}
return new TokenNumber($result);
}

View file

@ -109,6 +109,9 @@ class MathExecutor
$this->tokenFactory->addFunction('elt', function ($arg1, $arg2, $arg3, $arg4) {
return $arg4 <= $arg3 ? $arg2 : $arg1;
}, 4);
$this->tokenFactory->addFunction('eq', function ($arg1, $arg2, $arg3, $arg4) {
return $arg4 == $arg3 ? $arg2 : $arg1;
}, 4);
$this->addComplexFunc();
}
@ -278,7 +281,7 @@ class MathExecutor
* @param int $places Count of arguments
* @return MathExecutor
*/
public function addFunction($name, $function = null, $places = 1)
public function addFunction($name, callable $function = null, $places = 1)
{
$this->tokenFactory->addFunction($name, $function, $places);