php 逆波兰式计算字符串公式

<?php
namespace calc;
/**
 * php简单实现算术表达式转换成逆波兰式,并求解。
 * 仅支持加减乘除四种运算
 * <pre>
 *  require 'Calc.php';
 *  $calc = new Calc('(1+9)/2');
 *  echo $calc->getExpression();
 *  echo $calc->calculate();
 * </pre>
 */
class Calc {

    protected $_stackOperator = array('@');
    protected $_stackOut = array();
    protected $_operator = array('@', '(', ')', '+', '-', '*', '/');
    protected $_priority = array('@' => 0, '(' => 10, ')' => 10, '+' => 20, '-' => 20, '*' => 30, '/' => 30);

    public function __construct($expression) {
        $this->convert($expression);
    }

    /**
     * 解析字符串表达式
     * 解析字符串表达式,将数字和运算符分离,用数组存储
     * @param string $expression
     * @return array
     */
    protected function expressionParase($expression) {
        $arr = str_split($expression);
        $data = $tmp = array();
        do {
            $item = array_shift($arr);
            if (in_array($item, $this->_operator)) {
                if ($tmp) {
                    array_push($data, implode('', $tmp));
                    $tmp = array();
                }
                array_push($data, $item);
            } else {
                array_push($tmp, $item);
            }

        } while(count($arr));
        array_push($data, implode('', $tmp));
        return $data;
    }

    /**
     * 生成逆波兰式
     * @param string $expression
     */
    protected function convert($expression) {
        foreach ($this->expressionParase($expression) as $char) {
            if (preg_match("/^[0-9]+(\.?[0-9]+)?$/", $char)) {
                array_push($this->_stackOut, $char);
            } else if (in_array($char, $this->_operator)) {
                if ('(' == $char) {
                    array_push($this->_stackOperator, $char);
                } else if (')' == $char) {
                    while (count($this->_stackOperator) > 1) {
                        $drop = array_pop($this->_stackOperator);
                        if ('(' == $drop) {
                            break;
                        } else {
                            array_push($this->_stackOut, $drop);
                        }
                    }
                } else {
                    while (count($this->_stackOperator)) {
                        $oTop = end($this->_stackOperator);
                        if ($this->_priority[$char] > $this->_priority[$oTop]) {
                            array_push($this->_stackOperator, $char);
                            break;
                        } else {
                            $drop = array_pop($this->_stackOperator);
                            array_push($this->_stackOut, $drop);
                        }
                    }
                }
            }
        }

        while (count($this->_stackOperator)) {
            $drop = array_pop($this->_stackOperator);
            if ('@' == $drop) {
                break;
            } else {
                array_push($this->_stackOut, $drop);
            }
        }
    }

    /**
     * 获取逆波兰式
     * @return string
     */
    public function getExpression() {
        return implode('', $this->_stackOut);
    }

    /**
     * 计算逆波兰式
     * @return int
     */
    public function calculate() {
        $stack = array();
        foreach ($this->_stackOut as $char) {
            if (preg_match("/^[0-9]+(\.?[0-9]+)?$/", $char)) {
                array_push($stack, $char);
            } else if (in_array($char, $this->_operator)) {
                $b = array_pop($stack);
                $a = array_pop($stack);

                array_push($stack, $this->operator($a, $b, $char));
            }
        }

        return end($stack);
    }

    protected function operator($a, $b, $o) {
        switch ($o) {
            case '+':
                return round(floatval($a) + floatval($b),2);
                break;
            case '-':
                return round(floatval($a) - floatval($b),2);
                break;
            case '*':
                return round(floatval($a) * floatval($b),2);
                break;
            case '/':
                return round(floatval($a) / floatval($b),2);
                break;
        }
    }
}

使用方法:

$calc = new Calc("1.1+2*0.6");
echo $calc->calculate();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_44056947

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值