PHP如何使用栈完成高级计算器
发布时间:2023-05-16 06:42:51
在PHP中使用栈可以实现一个基本的高级计算器,可以进行加减乘除、求幂、括号优先级等操作。下面将通过步骤来讲解如何使用PHP实现一个高级计算器。
步:定义栈类
首先,我们需要定义一个栈类,包含以下方法:
1. push($item):将元素$item入栈
2. pop():从栈顶取出元素
3. isEmpty():判断栈是否为空
4. top():获取栈顶元素
5. clear():清空栈
代码如下:
class Stack {
private $stack = array();
public function push($item) {
array_push($this->stack, $item);
}
public function pop() {
return array_pop($this->stack);
}
public function isEmpty() {
return empty($this->stack);
}
public function top() {
return end($this->stack);
}
public function clear() {
$this->stack = array();
}
}
第二步:定义高级计算器类
接下来,我们需要定义一个高级计算器类,包含以下方法:
1. evaluate($expression):计算表达式的值
2. isOperator($char):判断字符是否是运算符
3. getPriority($char):获取运算符的优先级
4. compute($left, $operator, $right):计算两个数字的结果
代码如下:
class Calculator {
private $numStack; // 数字栈
private $opStack; // 运算符栈
function __construct() {
$this->numStack = new Stack();
$this->opStack = new Stack();
}
public function evaluate($expression) {
$i = 0;
while ($i < strlen($expression)) {
$char = $expression[$i];
if (is_numeric($char)) { // 如果是数字,入栈
$num = $this->getNumber($expression, $i);
$this->numStack->push($num);
} else if ($this->isOperator($char)) { // 如果是操作符,入栈
while (!$this->opStack->isEmpty() && $this->getPriority($this->opStack->top()) >= $this->getPriority($char)) {
$this->compute();
}
$this->opStack->push($char);
} else if ($char == '(') { // 如果是左括号,入栈
$this->opStack->push($char);
} else if ($char == ')') { // 如果是右括号,计算到左括号为止
while ($this->opStack->top() != '(') {
$this->compute();
}
$this->opStack->pop();
}
$i++;
}
while (!$this->opStack->isEmpty()) { // 计算剩余的表达式
$this->compute();
}
return $this->numStack->pop();
}
private function isOperator($char) {
return in_array($char, array('+', '-', '*', '/', '^'));
}
private function getPriority($char) {
if ($char == '*' || $char == '/') {
return 2;
} else if ($char == '+' || $char == '-') {
return 1;
} else if ($char == '^') {
return 3;
} else {
return 0;
}
}
private function compute() {
$right = (int) $this->numStack->pop();
$left = (int) $this->numStack->pop();
$operator = $this->opStack->pop();
switch ($operator) {
case '+':
$result = $left + $right;
break;
case '-':
$result = $left - $right;
break;
case '*':
$result = $left * $right;
break;
case '/':
$result = $left / $right;
break;
case '^':
$result = pow($left, $right);
break;
}
$this->numStack->push($result);
}
private function getNumber($expression, &$i) {
$num = 0;
while ($i < strlen($expression) && is_numeric($expression[$i])) {
$num = $num * 10 + (int) $expression[$i];
$i++;
}
$i--;
return $num;
}
}
第三步:测试代码
最后,我们来测试一下此计算器的功能:
$calculator = new Calculator();
echo $calculator->evaluate("2+3*4"); // 输出14
echo $calculator->evaluate("(2+3)*4"); // 输出20
echo $calculator->evaluate("2^3"); // 输出8
运行结果:
14 20 8
以上代码实现了PHP如何使用栈完成高级计算器,可以进行加减乘除、求幂、括号优先级等操作。如果想要更加复杂的计算器,可以扩展这个类。
