[英]how to add together the values from the RPN algorithm
I'm writing calculator that calculates values from expressions:我正在编写从表达式计算值的计算器:
3+(23/24)*34/24 3+(23/24)*34/24
I used RPN algorithm: https://en.wikipedia.org/wiki/Reverse_Polish_notation我使用了RPN算法: https://en.wikipedia.org/wiki/Reverse_Polish_notation
I have now sorted expression in String:我现在已经对字符串中的表达式进行了排序:
3 23 24 / 34 * 24 / + 3 23 24 / 34 * 24 / +
I don't have any idea how can I get value from this expression.我不知道如何从这个表达式中获得价值。
Thx谢谢
The basic idea behind RPN is that there is a stack that all the arguments get put on, then taken off for an operation. RPN 背后的基本思想是有一个堆栈,所有 arguments 都放在上面,然后取下进行操作。
For this set, the basic flow will be:对于这个集合,基本流程是:
Element元素 | Stack堆 | a一种 | b b |
---|---|---|---|
push 3推 3 | 3 3个 | ||
push 23推 23 | 3,23 3,23 | ||
push 24推24 | 3,23,24 3,23,24 | ||
-divide -划分 | |||
pop b流行音乐 | 3,23 3,23 | 24 24 | |
pop a弹出一个 | 3 3个 | 23 23 | 24 24 |
push a/b推a/b | 3, 0.9583 3、0.9583 | ||
end-divide端分 | |||
push 34推34 | 3, 0.9583, 34 3, 0.9583, 34 | ||
-multiply -乘 | |||
pop b流行音乐 | 3, 0.9583 3、0.9583 | 34 34 | |
pop a弹出一个 | 3 3个 | 0.9583 0.9583 | 34 34 |
push a*b推a*b | 3, 32.5833 3、32.5833 | ||
end-multiply尾乘 | |||
push 24推24 | 3, 32.5833, 24 3、32.5833、24 | ||
-divide -划分 | |||
pop b流行音乐 | 3, 32.5833 3、32.5833 | 24 24 | |
pop a弹出一个 | 3 3个 | 32.5833 32.5833 | 24 24 |
push a/b推a/b | 3, 1.3576 3、1.3576 | ||
end-divide端分 | |||
add添加 | |||
pop b流行音乐 | 3 3个 | 1.3576 1.3576 | |
pop a弹出一个 | 3 3个 | 1.3576 1.3576 | |
push a+b推a+b | 4.3576 4.3576 | ||
end-add结束添加 |
pop solution!弹出解决方案!
The basic algorithm is based on a stack-like structure基本算法基于类似堆栈的结构
For each token in the expression:对于表达式中的每个标记:
Eg:例如:
"3 23 24 / 34 * 24 / +"
Stack
3: push 3 | 3
23: push 23 | 3 23
24: push 24 | 3 23 24
/: pop (24), pop (23), push 23/24 | 3 0.95
34: push 34 | 3 0.95 34
*: pop (34), pop (0.95), push 0.95*34 | 3 32.58
24: push 24 | 3 32.58 24
/: pop (24), pop (32.58), push 32.58/24 | 3 1.35
+: pop (1.35), pop (3), push 3+1.35 | 4.35
The last value that remains in the stack is the result保留在堆栈中的最后一个值是结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.