在 PHP 中,创建计算器需要解析和计算用户输入的数学表达式。这可能具有挑战性,因为它涉及处理用户输入和应用数学运算。
一种推荐的方法是利用调车场算法。该算法将数学表达式转换为逆波兰表示法 (RPN),更易于计算。
以下是使用调车场算法的简化示例:
// Terminal expression abstract class abstract class TerminalExpression { public function operate() { return $this->value; } public function isOperator() { return false; } public function isParenthesis() { return false; } public function isNoOp() { return false; } } // Operator expression abstract class abstract class Operator extends TerminalExpression { public function isOperator() { return true; } } // Stack implementation class Stack { private $data = []; public function push($element) { $this->data[] = $element; } public function peek() { return end($this->data); } public function pop() { return array_pop($this->data); } } // Math class for evaluation class Math { public function evaluate($expression) { $stack = $this->parse($expression); return $this->run($stack); } private function parse($expression) { $tokens = $this->tokenize($expression); $output = new Stack(); $operators = new Stack(); foreach ($tokens as $token) { $type = TerminalExpression::factory($token); if ($type->isOperator()) { $this->parseOperator($type, $output, $operators); } elseif ($type->isParenthesis()) { $this->parseParenthesis($type, $output, $operators); } else { $output->push($type); } } while (($op = $operators->pop())) { if ($op->isParenthesis()) { throw new RuntimeException('Mismatched Parenthesis'); } $output->push($op); } return $output; } private function run(Stack $stack) { while (($operator = $stack->pop()) && $operator->isOperator()) { $value = $operator->operate($stack); if ($value !== null) { $stack->push(TerminalExpression::factory($value)); } } return $operator ? $operator->render() : $this->render($stack); } protected function tokenize($string) { return preg_split('((\d+|\+|-|\(|\)|\*|/)|\s+)', $string, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); } } $math = new Math(); $answer = $math->evaluate('(2 + 3) * 4'); var_dump($answer); // int(20)
这个例子演示了如何使用调车场算法来解析和评估一个简单的数学表情。
以上是如何使用调车场算法在 PHP 中构建计算器?的详细内容。更多信息请关注PHP中文网其他相关文章!