算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。前缀表达式指二元运算符位于两个运算数之前,例如2+3*(7-4)+8/4
的前缀表达式是:+ + 2 * 3 - 7 4 / 8 4
。请设计程序计算前缀表达式的结果值。
输入格式:
输入在一行内给出不超过30个字符的前缀表达式,只包含+
、-
、*
、/
以及运算数,不同对象(运算数、运算符号)之间以空格分隔。
输出格式:
输出前缀表达式的运算结果,保留小数点后1位,或错误信息ERROR
。
样例:
+ + 2 * 3 - 7 4 / 8 4
输出样例:
13.0
前缀表达式我们只需要倒着跑用栈来模拟这个过程就可以了,用stringstream将每个数字和字符用string数组储存起来因为数字可能是负数或者好几位数 在碰到运算符时保证运算符前有两个数字能进行运算并且进行除法时分母不能为0并且到最后栈中一定只剩一个数字,否则直接输出ERROR
#include "bits/stdc++.h"
using namespace std;
int main() {
string s;
string str[1005];
getline(cin, s);
stringstream ss(s);
string b;
int cnt = 0;
while (ss >> b) {
str[++cnt] = b;
}
stack<double> st;
for (int i = cnt; i >= 1; i--) {
if (str[i] == "+" || str[i] == "-" || str[i] == "*" || str[i] == "/") {
if (st.size() < 2) {
cout << "ERROR" << endl;
return 0;
} else {
double a = st.top();
st.pop();
double b = st.top();
st.pop();
if (str[i] == "+") {
st.push(a + b);
} else if (str[i] == "-") {
st.push(a - b);
} else if (str[i] == "*") {
st.push(a * b);
} else if (str[i] == "/") {
if (b == 0) {
cout << "ERROR" << endl;
return 0;
} else {
st.push(a / b);
}
}
}
} else {
double k = stod(str[i]) * 1.0;
st.push(k);
}
}
if (st.size() == 1) printf("%.1f\n", st.top());
else cout << "ERROR" << endl;
return 0;
}