上篇博客我们已经将中缀表达式正确的转换为后缀表达式了。
So how does the suffix expression work? The numbers and operators in the suffix expression are required. If the current element is an operator: 1. The right operand is popped out of the stack; 2. The left operand is popped out of the stack; 3. Operation according to the symbol; 4. Presses the result of the operation into the stack. When the traversal is finished, the only number in the stack is the result of the operation.
The pseudo code is used to describe it:
In this case we have to take into account the division in the mathematical operation (except 0), if the floating point operation, you should avoid the code directly compared with 0.
Specific to the code is:
QString qcalculatordec::calculate (qqueue<qstring>& exp)
{
QString ret = "Error";
Qstack<qstring> Stack;
while (!exp.isempty ()) {QString E = Exp.dequeue (); if (Isnumber (e)) {Stack.push (e); } else if (Isoperator (e)) {QString RP =!stack.isempty ()? stack.po P (): ""; QString LP =!stack.isempty ()? Stack.pop (): ""; QString result = calculate (LP, E, RP); if (Result! = "Error") {Stack.push (result); } else {break; }} else {break; }} if (Exp.isempty () && (stack.size () = = 1) && isnumber (Stack.top ())) { ret = Stack.pop (); } return ret;} In which the specific do arithmetic of the generationThe code is: QString qcalculatordec::calculate (QString L, QString op, QString r) {QString ret = "Error"; if (Isnumber (L) && Isnumber (R)) {Double LP = l.todouble (); Double RP = r.todouble (); if (op = = "+") {ret.sprintf ("%f", LP + RP); } else if (op = = "-") {ret.sprintf ("%f", LP-RP); } else if (op = = "*") {ret.sprintf ("%f", LP * RP); } else if (op = = "/") {const double p = 0.000000001; if ((-P < RP) && (RP < P)) {ret = "Error"; } else {ret.sprintf ( "%f", LP/RP); }} else {ret = "Error"; }} return ret;}
So let's put the logic-related functions in the expression function:
We run the expression in the main function (3-8) * (2-6) and the result is as follows:
We see that the program has been able to correctly calculate the results of the expression, then the next step is how to connect the results with the GUI, we will do the relevant experiments later.
以上内容来自狄泰软件学院的QT教程,欢迎大家一起来学习,可以加我QQ:243343083,一起学习。狄泰技术交流群:199546072
QT's calculator analytic algorithm