#include <iostream>#include <stack>using namespace std;//棧內優先級int isp(char a){ switch (a) { case '+': case '-': return 3; case '*': case '/': return 5; case '(': return 1; case ')': return 6; case '#': return 0; default: return -1; break; }}//棧外優先級int icp(char a){ switch (a) { case '+': case '-': return 2; case '*': case '/': return 4; case '(': return 6; case ')': return 1; case '#': return 0; default: return -1; break; }}//計算函數int cal(int a, int b, char c){ switch (c) { case '+': return b + a; case '-': return b - a; case '*': return b * a; default: return b / a; }}char in_order_exPRession[1000];//中綴表達式char post_order_expression[1000];//后綴表達式stack<int> calculation;//計算的時候到棧stack<char> tmp;//中綴改后綴的時候到過渡棧int i = 0, j = 0;int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!/n"; cout << "請輸入中綴表達式,并以#結尾" << endl; cin >> in_order_expression; // for (int k = 0; in_order_expression[k] != '#'; k++) {// cout <<in_order_expression[k] << " ";// } tmp.push('#');// int a = 0;// for (a = 0; in_order_expression[a] != '#'; a++);// int len = a + 1; while (!tmp.empty()) { //如果是數字,直接輸出到后綴表達式里 if (in_order_expression[i] >= '0' && in_order_expression[i] <= '9') { post_order_expression[j++] = in_order_expression[i++]; } else { //如果是符號的話,則根據isp和icp的大小執行相應的動作 if (icp(in_order_expression[i]) > isp(tmp.top())) { tmp.push(in_order_expression[i++]); } //這里的i不能++,要保證出棧并輸出之后還能繼續對這個符號進行操作 else if (icp(in_order_expression[i]) < isp(tmp.top())) { post_order_expression[j++] = tmp.top(); tmp.pop(); } //只有左右括號的時候會執行這個操作 else { tmp.pop(); } } cout << i << "次迭代成功" << endl;//做個標記 }//計算部分 i = 0; do { //如果是數字,直接入棧 if (post_order_expression[i] >= '0' && post_order_expression[i] <= '9') { calculation.push(post_order_expression[i++] - '0'); } else { //符號的話,就要根據符號的類型,計算棧中最上面兩個數字的結果,然后再入棧,保證每次 //計算的時候,棧里永遠有兩個數字 int temp1 = calculation.top(); calculation.pop(); int temp2 = calculation.top(); calculation.pop(); calculation.push(cal(temp1, temp2, post_order_expression[i++])); } cout << i << "次計算成功" << endl;//做個標記 }while (i < j); cout << calculation.top() << endl; return 0;}
新聞熱點
疑難解答
圖片精選