• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

逆波兰表达式计算,该如何解决

php 搞代码 3年前 (2022-01-23) 29次浏览 已收录 0个评论

逆波兰表达式计算
最近在整理资料时发现了一些以前收藏的有趣代码
计划逐步将他们移植到 PHP 供有兴趣的人参考

PHP code

<!---ecms Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->/** * 逆波兰表达式计算 * 中缀转后缀 **/function postfix($infix) {    $priority = array( //算符优先级        '+' => 1, '-' => 1,        '*' => 2, '/' => 2,        '(' => 0, ')' => 0,        '.' => 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0        );    $stack = array(); //符号栈    $data = array(); //数值栈     $i = $top = 0;    $last = -1;    $len = strlen($infix);    while($i= $priority[$infix{$i}]) {                    postfix_callback(array_shift($stack), $data);                }                array_unshift($stack, $infix{$i});                break;            case ')':                if($t != '') array_unshift($data, $t);                $t = '';                while($stack[0] != '(') {                    postfix_callback(array_shift($stack), $data);                }                array_shift($stack);                break;            default:                if($i > $last+1 && $t != '') {                    array_unshift($data, $t);                    $t = '';                }                $t .= $infix{$i};                $last = $i;                break;         }        $i++;    }    while($stack) {        postfix_callback(array_shift($stack), $data);    }    return $data[0];}/** * postfix 的工作函数 * 用于计算表达式的值 **/function postfix_callback($ch, &$data) {    $b = array_shift($data);    switch($ch) {        case '+':            $data[0] += $b;            break;        case '-':            $data[0] -= $b;            break;        case '*':            $data[0] *= $b;            break;        case '/':            $data[0] /= $b;            break;    }}

测试例

PHP code

<!---ecms Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->echo postfix( '(2+3)*(3+4)' ); //out 35

——解决方案——————–
先回贴在看
——解决方案——————–
这个好东西。

——解决方案——————–
前排占座, 板主老大给力.
——解决方案——————–
前排占座本文@来#源gaodai$ma#com搞$$代**码网搞代gaodaima码, 板主老大给力.


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:逆波兰表达式计算,该如何解决
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址