

1 2 //轉換為后綴表達式,實現最主要功能 3 void MainWindow::toPostfix () 4 { 5 QString exp = ui->lineEdit->text (); 6 //QString exp = "0.3/(5*2+1)", postfix; 7 8 QString tmp = exp; 9 10 int j; 11 //如果只有單個數字時 12 for (j = 0; j < tmp.size () && (tmp[j].isDigit () || tmp[j] == '.'); j++) { 13 postFix.push_back (tmp[j]); 14 } 15 if (j == tmp.size ()) { 16 postFix.push_back (' '); 17 return; 18 } 19 postFix.clear (); 20 21 for (int i = 0; i < exp.size (); i++) 22 { 23 qDebug() << i << exp[i]; 24 if (exp[i].isDigit () || exp[i] == '.') {//為數字或者小數點 25 postFix.push_back (exp[i]); //直接添加到后綴表達式后面 26 } 27 else if (exp[i] == '(') { //入操作符棧 28 opStack.push (exp[i]); 29 } 30 else if (exp[i] == ')') { //遇到右括號,就轉換成空格添加到后綴表達式中 31 postFix.push_back (' '); 32 while (opStack.top () != '(') 33 { 34 //只要遇到右括號,則在操作符棧中將棧頂下一次出現'('前的操作符全部依次添加到后綴表達式后面 35 //因為進棧的時候,是棧頂操作符優先級低;所以出棧的時候,優先級高->低依次添加到后綴表達式后 36 postFix.push_back (opStack.pop ()); 37 qDebug() << postFix; 38 } 39 opStack.pop (); //遇到右括號一次,左括號也相應少一次 40 } 41 //運算符比棧頂的優先級高時,入棧頂 42 else if (getLevel (exp[i]) > getLevel (opStack.top ())) 43 { 44 //將操作符和操作數用空格分開 45 postFix.push_back (' '); 46 opStack.push (exp[i]); 47 } 48 else { 49 postFix.push_back (' '); qDebug() << postFix; 50 //當操作符比棧頂的操作符優先級低時,從棧頂(彈出)pop()運算符,添加到后綴表達式中 51 while (getLevel (exp[i]) <= getLevel (opStack.top ())) 52 postFix.push_back (opStack.pop ()); 53 opStack.push (exp[i]); //棧頂優先級低則,入棧 54 } 55 } 56 while (opStack.top () != '#') { //結束標志 57 QChar c = opStack.pop (); 58 postFix.push_back (' '); //操作符之間用空格分開 59 postFix.push_back (c); //將棧中剩余的操作符添加到后綴表達式后面 60 } 61 qDebug() << postFix; 62 }
1 //計算后綴表達式 2 3 void MainWindow::evaluation () 4 { 5 QString tmp; 6 QStack<double> ans; 7 8 for (int i = 0; i < postFix.size (); i++) 9 { 10 qDebug() << postFix[i] << i; 11 if (postFix[i].isDigit () || postFix[i] == '.') 12 tmp.push_back (postFix[i]); 13 else if (postFix[i] == ' ') { //相當於遇到一個操作符或者是括號 14 if (!tmp.isEmpty ()) 15 { 16 ans.push (tmp.toDouble ()); 17 tmp.clear (); 18 } 19 qDebug() << ans.top () << tmp.isEmpty (); 20 } 21 else { //遇到操作符,從棧中彈出兩個數,進行計算,並將結果入棧 22 double a = 0, b = 0; 23 switch (postFix[i].cell ()) { 24 case '!': a = ans.pop ();ans.push (Fac(a)); break; 25 26 case '+': a = ans.pop (); b = ans.pop (); 27 ans.push (b + a); break; 28 29 case '-': a = ans.pop (); b = ans.pop (); 30 ans.push (b - a); break; //應該是后彈出棧的-先彈出棧的 31 32 case '*': a = ans.pop (); b = ans.pop (); 33 ans.push (b * a); break; 34 case '/':a = ans.pop (); b = ans.pop (); 35 ans.push (b / a); break; 36 37 case '%': a = ans.pop (); b = ans.pop (); 38 ans.push ((int)b % (int)a); break; 39 40 case '^': a = ans.pop (); b = ans.pop (); 41 ans.push (Pow(b, a)); break; 42 default: 43 break; 44 } 45 qDebug() << ans.top () << "top"; 46 } 47 } 48 ui->lineEdit->setText (QString::number (ans.top ())); 49 }
//全部代碼見,百度雲
鏈接: https://pan.baidu.com/s/1qXQKPTM 密碼: qwfn
