当你有一个字符串形式的简单方程时,最实用的方法是将字符串解析为prefix
或postfix
符号,然后对其进行相应的评估......
假设原始字符串是infix
(人类用来学习基本数学的符号),例如......
1000 * (200+3928)/2333
然后,您将其转换postfix
为获得...
1000, 200, 3928, +, *, 2333, /
使用这种表示法,计算机可以使用简单的循环和堆栈轻松评估表达式......
我不会发布实际代码,因为我想把有趣的部分留给你,但如果你想用伪代码先行一步,这里就...
infix to postfix :
create empty array `postfix` and `temp`
split the expression up into an array `A` by each operand/operator
foreach token in `A`:
if char is operand :
push to postfix stack
if char is open parenthesis:
push to temp stack
if char is close parenthesis:
while top of temp stack != '(' :
push top of temp stack to postfix stack
pop top of temp stack
end while
pop top of temp stack
if char is operator:
while temp stack isn't empty *and* top of temp stack != '(' *and* precendence(char) <= precendence(top of temp stack) :
push top of temp stack to postfix stack
pop top of temp stack
end while
push char to temp stack
end for loop
while temp stack is not empty
push top of temp stack to postfix stack
pop top of temp stack
end while
return postfix stack (will be your postfix stack to evaluate)
evaluate postfix stack:
create array A
foreach token in postfix stack:
if char is operand:
push to A stack
if char is operator:
int x = pop A stack
int y = pop A stack
result = x (operation) y
push result to A stack
end for loop
return top of A stack (this will be the final result)