omnicron / infix-calculator
基本中缀表达式求解器
0.3.4
2021-10-11 10:53 UTC
Requires
- php: >=7.4
Requires (Dev)
- phpunit/phpunit: ^9
README
InfixCalculator是一个基本的中缀数学表达式求解器。
目前,它只支持
- 数字(整数和小数)
- 括号
- 算术运算符:+ - * / ^
通过Composer安装
使用以下命令安装最新版本
composer require omnicron/infix-calculator
用法
获取最终结果
<?php use \Omnicron\InfixCalculator\Calculator; // create a Calculator object $calculator = new Calculator; // calculate the result of an expression $result = $calculator->solve('3 + 5 * (2^2 + 1)'); // write the result (28) echo $result.PHP_EOL;
获取求解表达式的所有步骤
<?php use \Omnicron\InfixCalculator\Calculator; // create a Calculator object $calculator = new Calculator; // get steps to solve an expression $steps = $calculator->getSteps('3 + 5 * (2^3 + 1) / (2^2 - 1)'); // show the steps echo implode(PHP_EOL, $steps).PHP_EOL; /* the steps will be shown like this: (3 + ((5 * ((2 ^ 3) + 1)) / ((2 ^ 2) - 1))) (3 + ((5 * (8 + 1)) / (4 - 1))) (3 + ((5 * 9) / 3)) (3 + (45 / 3)) (3 + 15) 18 */
为什么?
主要是因为我想尝试自己编写一个解析器。
此外,我计划使这个库更加完整和可定制。目前,就享受这个非常基本的表达式求解器吧!
作者
Dany Thach - d.thach4@gmail.com
许可证
InfixCalculator遵循MIT许可证。