7-21 求前缀表达式的值 (25 分)
算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。前缀表达式指二元运算符位于两个运算数之前,例如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 <sstream>
using namespace std;
bool isNumber(const string& str) { //判断字符串是否为数字
istringstream sin(str);
double test;
return sin >> test && sin.eof();
}
double calc() {
string str;
cin >> str;
if (isNumber(str))
return stod(str);
switch (str[0]){
case '+': return calc() + calc();
case '-': return calc() - calc();
case '*': return calc() * calc();
case '/':
double a = calc(), b = calc();
if (b == 0) {
cout << "ERROR" << endl;
exit(0);
}
return a / b;
}
}
int main() {
printf("%0.1lf\n", calc());
return 0;
}
非递归版:
#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
#include <vector>
using namespace std;
bool isNumber(const string& str) { //判断字符串是否为数字
istringstream sin(str);
double test;
return sin >> test && sin.eof();
}
int main() {
string str;
vector<string> exp;
while (cin >> str) {
exp.push_back(str);
if (getchar() == '\n')
break;
}
double a, b;
vector<double> result;
reverse(exp.begin(), exp.end());
for (string& str : exp) {
if (isNumber(str))
result.push_back(stod(str));
else {
a = result.back(); result.pop_back();
b = result.back(); result.pop_back();
if (str == "+") result.push_back(a + b);
else if (str == "-") result.push_back(a - b);
else if (str == "*") result.push_back(a * b);
else {
if (b == 0) {
cout << "ERROR" << endl;
return 0;
}
result.push_back(a / b);
}
}
}
printf("%0.1lf", result.back());
return 0;
}