算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。前缀表达式指二元运算符位于两个运算数之前,例如2+3*(7-4)+8/4
的前缀表达式是:+ + 2 * 3 - 7 4 / 8 4
。请设计程序计算前缀表达式的结果值。
输入格式:
输入在一行内给出不超过30个字符的前缀表达式,只包含+
、-
、*
、\
以及运算数,不同对象(运算数、运算符号)之间以空格分隔。
输出格式:
输出前缀表达式的运算结果,保留小数点后1位,或错误信息ERROR
。
输入样例:
+ + 2 * 3 - 7 4 / 8 4
输出样例:
13.0
#include<iostream> #include<string> #include<vector> #include<stack> #include<stdio.h> using namespace std; vector<string>s; stack<float>st; int main() { string c; while (cin >> c) { s.push_back(c); if (getchar() == '\n') break; } /*for (int i = 0; i < s.size(); i++) { cout << s[i]<<" "; } cout << endl; system("pause");*/ float temp, st1, st2; for (int i = s.size()-1; i >=0; i--) { if (s[i] == "+") { st1 = st.top(); st.pop(); st2 = st.top(); st.pop(); temp = st1 + st2; st.push(temp); continue; } if (s[i] == "-") { st1 = st.top(); st.pop(); st2 = st.top(); st.pop(); temp = st1 - st2; st.push(temp); continue; } if (s[i] == "*") { st1 = st.top(); st.pop(); st2 = st.top(); st.pop(); temp = st1 * st2; st.push(temp); continue; } if (s[i] == "/") { st1 = st.top(); st.pop(); st2 = st.top(); st.pop(); if (st2 == 0) { cout << "ERROR"; return 0; } temp = st1 / st2; st.push(temp); continue; } st.push(atof(s[i].c_str())); } temp = st.top(); st.pop(); if (!st.empty()) cout << "ERROR"; else printf("%.1f", temp); return 0; }