对后缀表达式进行计算,得到表达式的值。
例如有后缀表达式:
2 1 + 3 *
其结果应为:
9
后缀表达式:
1 3 5 * + 7 9 / -
其结果应为:
15.222
后缀表达式:
1 3 + 5 7 - * 9 /
其结果应为:
-0.889
后缀表达式计算程序如下:
1 // 后缀表达式的计算 2 #include <iostream> 3 #include <sstream> 4 #include <vector> 5 #include <stack> 6 #include <map> 7 #include <string> 8 using namespace std; 9 10 void get_postfix(vector<string>& postf) 11 { 12 postf.clear(); 13 string line; 14 getline(cin, line); 15 istringstream sin(line); 16 string tmp; 17 while (sin >> tmp) 18 { 19 postf.push_back(tmp); 20 } 21 } 22 23 void init_op(map<string, int>& ops) 24 { 25 ops.clear(); 26 ops["+"] = 100; 27 ops["-"] = 100; 28 ops["*"] = 200; 29 ops["/"] = 200; 30 ops["("] = 1000; 31 ops[")"] = 0; 32 } 33 34 bool is_operator(const string& hs, const map<string, int>& ops) 35 { 36 map<string, int>::const_iterator cit = ops.find(hs);\ 37 if (cit != ops.end()) 38 { 39 return true; 40 } 41 else 42 { 43 return false; 44 } 45 } 46 47 double cal_post(const vector<string>& postf, const map<string, int>& ops) 48 { 49 stack<double> or_st; 50 double operand = 0.0, a = 0.0, b = 0.0, c = 0.0; 51 for (vector<string>::size_type i = 0; i != postf.size(); ++i) 52 { 53 if (!is_operator(postf[i], ops)) 54 { 55 operand = static_cast<double>(atof(postf[i].c_str())); 56 or_st.push(operand); 57 } 58 else 59 { 60 switch (postf[i][0]) 61 { 62 case '+': 63 b = or_st.top(); 64 or_st.pop(); 65 a = or_st.top(); 66 or_st.pop(); 67 c = a + b; 68 or_st.push(c); 69 break; 70 case '-': 71 b = or_st.top(); 72 or_st.pop(); 73 a = or_st.top(); 74 or_st.pop(); 75 c = a - b; 76 or_st.push(c); 77 break; 78 case '*': 79 b = or_st.top(); 80 or_st.pop(); 81 a = or_st.top(); 82 or_st.pop(); 83 c = a * b; 84 or_st.push(c); 85 break; 86 case '/': 87 b = or_st.top(); 88 or_st.pop(); 89 a = or_st.top(); 90 or_st.pop(); 91 c = a / b; 92 or_st.push(c); 93 break; 94 default: 95 break; 96 } 97 } 98 } 99 if (or_st.size() == 1) 100 { 101 return or_st.top(); 102 } 103 else 104 { 105 return -10000000000000.0; 106 } 107 } 108 109 int main() 110 { 111 map<string, int> ops; 112 init_op(ops); 113 vector<string> postf; 114 115 while (1) 116 { 117 get_postfix(postf); 118 double ret = cal_post(postf, ops); 119 cout << ret << endl << endl; 120 } 121 122 system("PAUSE"); 123 return 0; 124 }