在PHP中,有两种常见的表达式计算算法:逆波兰表达式算法和中缀表达式算法。
逆波兰表达式的计算步骤:
示例代码:
function evaluateRPN($expression) {
$stack = [];
$operators = ['+', '-', '*', '/'];
foreach ($expression as $token) {
if (is_numeric($token)) {
array_push($stack, $token);
} else if (in_array($token, $operators)) {
$operand2 = array_pop($stack);
$operand1 = array_pop($stack);
switch ($token) {
case '+':
array_push($stack, $operand1 + $operand2);
break;
case '-':
array_push($stack, $operand1 - $operand2);
break;
case '*':
array_push($stack, $operand1 * $operand2);
break;
case '/':
array_push($stack, $operand1 / $operand2);
break;
}
}
}
return array_pop($stack);
}
$expression = [5, 3, '+', 2, '*'];
$result = evaluateRPN($expression);
echo $result; // 输出 16
中缀表达式的计算步骤:
示例代码:
function evaluateInfix($expression) {
$stack = [];
$queue = [];
$operators = ['+', '-', '*', '/'];
foreach ($expression as $token) {
if (is_numeric($token)) {
array_push($queue, $token);
} else if ($token == '(') {
array_push($stack, $token);
} else if ($token == ')') {
while (end($stack) != '(') {
array_push($queue, array_pop($stack));
}
array_pop($stack); // 弹出左括号
} else if (in_array($token, $operators)) {
while (!empty($stack) && end($stack) != '(' && getPriority(end($stack)) >= getPriority($token)) {
array_push($queue, array_pop($stack));
}
array_push($stack, $token);
}
}
while (!empty($stack)) {
array_push($queue, array_pop($stack));
}
foreach ($queue as $token) {
if (is_numeric($token)) {
array_push($stack, $token);
} else if (in_array($token, $operators)) {
$operand2 = array_pop($stack);
$operand1 = array_pop($stack);
switch ($token) {
case '+':
array_push($stack, $operand1 + $operand2);
break;
case '-':
array_push($stack, $operand1 - $operand2);
break;
case '*':
array_push($stack, $operand1 * $operand2);
break;
case '/':
array_push($stack, $operand1 / $operand2);
break;
}
}
}
return array_pop($stack);
}
function getPriority($operator) {
switch ($operator) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}
$expression = [5, '+', 3, '*', 2];
$result = evaluateInfix($expression);
echo $result; // 输出 11
以上是两种常见的表达式算法在PHP中的实现方法。根据实际需求选择适合的算法来计算表达式。
下一篇:php 中文转拼音带音标
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站