数学表达式求解算法

时间:2013-10-15 19:39:44

标签: php math

我的上一个问题被搁置,因为问题不明确。

使用特定查询再次发布

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

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

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

我的第一个问题是,这是解决这类问题的理想语言。此外,是否有任何内置的解决方案,以便我不必重新发明轮子

提前致谢

1 个答案:

答案 0 :(得分:0)

Stacks可以帮助你,考虑:1 +(2 + 3)

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

当你找到一个数字时,放入数字堆栈,当你找到一个操作员时,放入操作员堆栈,当你找到"("什么也不做,当你找到一个& #34;)",获取两个数字的堆栈和一个运算符,对这两个数字进行计算并再次放入数字堆栈中,参见代码循环:

//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

我希望它可以帮到你