算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。前缀表达式指二元运算符位于两个运算数之前,例如2+3*(7-4)+8/4
的前缀表达式是:+ + 2 * 3 - 7 4 / 8 4
。请设计程序计算前缀表达式的结果值。
输入格式:
输入在一行内给出不超过30个字符的前缀表达式,只包含+
、-
、*
、/
以及运算数,不同对象(运算数、运算符号)之间以空格分隔。
输出格式:
输出前缀表达式的运算结果,保留小数点后1位,或错误信息ERROR
。
输入样例:
+ + 2 * 3 - 7 4 / 8 4
输出样例:
13.0
注意这里的输入问题,数字前面可能有+-,如+123, 还有可能是带小数点的,123.12,这里使用atof将char*转化为double;
波拉式的求法:从右往左将数字入栈,遇到符号出栈2个数字做计算,如果栈中元素没有2个则输出ERROR;最后栈中的元素为答案;
#include<iostream>
#include<algorithm>
#include<stack>
#include<string>
#include<iomanip>
#include<vector>
using namespace std;
string str;
vector<string>v;
stack<double>stk;
bool isNum(string s) {
if (s.size() > 1) return 1;
else if (s[0] >= '0' && s[0] <= '9') return 1;
else return 0;
}
int main() {
while (cin >> str) {
v.push_back(str);
}
for (vector<string>::reverse_iterator it = v.rbegin(); it != v.rend(); it++) {
if (isNum(*it)) {
string t = *it;
stk.push(atof(t.c_str()));//char* 转化为double
}
else
{
if (stk.size() < 2) {
cout << "ERROR";
return 0;
}
double a, b;
a = stk.top();
stk.pop();
b = stk.top();
stk.pop();
if (*it == "+") {
stk.push(a + b);
}
else if (*it == "-") {
stk.push(a - b);
}
else if (*it == "*") {
stk.push(a * b);
}
else if (*it == "/") {
if (b == 0) {
cout << "ERROR";
return 0;
}
stk.push(a / b);
}
}
}
if (stk.size() == 1) cout << fixed << setprecision(1) << stk.top();
else cout << "ERROR";
return 0;
}