题目:
算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。前缀表达式指二元运算符位于两个运算数之前,例如2+3*(7-4)+8/4的前缀表达式是:+ + 2 * 3 - 7 4 / 8 4。请设计程序计算前缀表达式的结果值。
输入格式:
输入在一行内给出不超过30个字符的前缀表达式,只包含+、-、*、/以及运算数,不同对象(运算数、运算符号)之间以空格分隔。
输出格式:
输出前缀表达式的运算结果,保留小数点后1位,或错误信息ERROR。
输入样例:
输出样例:
pta测试链接
pta测试截图

c++代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| #include<iostream> #include<stack> #include <string> #include<iomanip> #include<sstream> using namespace std; stack <double> s; bool AllisNum(string str) { stringstream sin(str); double d; char c; if (!(sin >> d)) { return false; } if (sin >> c) { return false; } return true; } double cal(double a, double b, char op) { if (op == '-') return a - b; else if (op == '+') return a + b; else if (op == '*') return a * b; else if (b == 0) { cout << "ERROR"; exit(0); } return a / b; } int main(void) { string str; string ss[200]; int nu = 0; double a, t1, t2, res; getline(cin, str); istringstream iss(str); while (iss >> str) { ss[nu] = str; nu++; } for (int i = nu- 1; i >= 0; --i) { if (AllisNum(ss[i])) { a = stod(ss[i]); string 转为 double “2.3”-->2.3 s.push(a); } else { t1 = s.top(); s.pop(); t2 = s.top(); s.pop(); s.push(cal(t1, t2, ss[i][0])); } } if (!s.empty()) { res = s.top(); printf("%.1lf\n", res); } return 0; }
|