【问题标题】:Mathematical Expressions Solving Algorithm数学表达式求解算法
【发布时间】:2013-10-23 18:03:59
【问题描述】:

由于问题不清楚,我之前的问题被搁置了。

使用特定查询再次发布

我的要求是使用 PHP 解决任何复杂的数学表达式。例如,

如果我有一个字符串“1(1+2)/3 + 4”,使用 BODMAS 规则,我必须解决它。但我还必须完成所有单独的步骤。

我提到的两个网站是:
http://www.careerbless.com/calculators/ScientificCalculator/
http://web2.0calc.com/

我的第一个问题是,哪种语言是解决这类问题的理想语言。另外,有没有可用的内置解决方案,这样我就不必重新发明轮子了

提前致谢

【问题讨论】:

  • ircmaxell 在他对this question的回答中提供了一个优秀(且安全)的后端公式评估器... 以获得使用的实际步骤,您可以在解析后和执行前显示堆栈
  • 您知道您可以编辑一个已关闭的问题而不是打开一个新问题,对吧?一旦问题得到解决,我们(社区)通常会重新提出问题。这就是搁置的意思。
  • @Mark Ba​​ker,谢谢,这就是我想要的。现在我可以在此基础上构建
  • eval() 可能正在运行这种计算器。
  • @kojiro,对不起,我会处理的

标签: php math


【解决方案1】:

堆栈可能会对您有所帮助,请考虑:1 + (2 + 3)

创建两个堆栈,一个是数字,另一个是运算符。

当你找到一个数字时,放入数字堆栈,当你找到一个运算符时,放入运算符堆栈,当你找到“(”时什么都不做,当你找到一个“)”时,得到两个数字堆栈和一个运算符,对这两个数字进行计算并再次放入数字堆栈中,参见代码循环:

//1 + (2 + 3)
operators = []
numbers = []

//I put the number in the numbers stack
//+ (2 + 3)
operators = []
numbers = [1]
-- 
// I put the operator in the operators stack
// (2 + 3)
operators = [+]
numbers = [1]
-- 
// 2 + 3)
//find a "(" char, do nothing
operators = [+]
numbers = [1]
-- 
// + 3)
operators = [+]
numbers = [1, 2]
-- 
// 3)
operators = [+, +]
numbers = [1, 2]
-- 
// )
operators = [+, +]
numbers = [1, 2, 3]
--
//found a ")", get two items of stack of numbers (3,2), and one item of operators stack (+), result is 5, put back in the stack of numbers 
operators = [+]
numbers = [1, 5]
--
//When finished string, get two elements and one operator until finish the stack
// get two elements of numbers stack (1,5) and one of operators stack +, result is 6

希望对你有帮助

【讨论】:

  • 这无济于事。试试:(23-654+891-874)*45422/4658。堆栈很有用,但上面的逻辑不会给出正确的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-23
  • 2011-02-25
  • 1970-01-01
  • 2011-11-07
  • 1970-01-01
相关资源
最近更新 更多