標籤:優先 vector empty -- 入棧 結果 tmp turn push
給一個包含小數的中綴運算式 求出它的值
首先轉換為尾碼運算式然後利用stack求出值
轉換規則:
如果字元為‘(‘ push
else if 字元為 ‘)‘
出棧運算子直到遇到‘(‘
else if 字元為‘+’,’-‘,’*‘,’/‘
{
if 棧為空白或者上一個運算子的優先順序小於當前運算子
push
else
{
運算子優先順序小於等於棧頂運算子的優先順序,出棧
然後!將當前運算子入棧!
}
}
代碼
#include<iostream>#include<cstdio>#include<cmath>#include<cstring>#include<sstream>#include<algorithm>#include<queue>#include<deque>#include<iomanip>#include<vector>#include<cmath>#include<map>#include<stack>#include<set>#include<fstream>#include<memory>#include<list>#include<string>using namespace std;typedef long long LL;typedef unsigned long long ULL;#define MAXN 1100#define L 31#define INF 1000000009#define eps 0.00000001/*1.000+2/4=((1+2)*5+1)/4=首先把中綴運算式轉換為尾碼運算式!(注意點運算子求值)轉換後的結果用一個string vector來表示然後從前到後求值,pop兩個數字 計算結果然後插入到stack中*/string str;vector<string> trans;stack<char> S;stack<float> cal;map<char, int> pri;void Read(){ string tmp; trans.clear(); while (!S.empty()) S.pop(); while (!cal.empty()) cal.pop(); for (int i = 0; i < str.size() - 1; i++)// 特殊考慮( ) . { if (str[i] == ‘(‘) { if (!tmp.empty()) { trans.push_back(tmp); tmp.clear(); } S.push(str[i]); } else if (str[i] == ‘)‘) { if (!tmp.empty()) { trans.push_back(tmp); tmp.clear(); } while (!S.empty() && S.top() != ‘(‘) { string ttt = ""; ttt.push_back(S.top()); trans.push_back(ttt); S.pop(); } if (!S.empty() && S.top() == ‘(‘) S.pop(); } else if (str[i] == ‘+‘ || str[i] == ‘-‘ || str[i] == ‘*‘ || str[i] == ‘/‘) { if (!tmp.empty()) { trans.push_back(tmp); tmp.clear(); } if (S.empty() || pri[S.top()]<pri[str[i]]) { S.push(str[i]); continue; } else { while (!S.empty() && pri[S.top()] >= pri[str[i]]) { string ttt = ""; ttt.push_back(S.top()); trans.push_back(ttt); S.pop(); } S.push(str[i]); } } else { tmp.push_back(str[i]); } } if (!tmp.empty()) { trans.push_back(tmp); tmp.clear(); } while (!S.empty()) { string ttt = ""; ttt.push_back(S.top()); trans.push_back(ttt); S.pop(); }}float solve()//計算轉化出的尾碼運算式的值{ while (!cal.empty()) cal.pop(); for (int i = 0; i < trans.size(); i++) { if (trans[i] == "+" || trans[i] == "-" || trans[i] == "*" || trans[i] == "/") { float a, b; a = cal.top(); cal.pop(); b = cal.top(); cal.pop(); if (trans[i] == "+") cal.push(a + b); else if (trans[i] == "-") cal.push(b - a); else if (trans[i] == "*") cal.push(a * b); else cal.push(b / a); } else { cal.push(atof(trans[i].c_str())); } } return cal.top();}int main(){ int n; cin >> n; pri[‘+‘] = pri[‘-‘] = 0, pri[‘*‘] = pri[‘/‘] = 1, pri[‘(‘] = pri[‘)‘] = -1; while (n--) { cin >> str; Read(); printf("%.2f\n",solve()); } return 0;}
中綴運算式求值 C++ Stack