http://acm.hdu.edu.cn/showproblem.php?pid=1237
表达式计算,方法是中缀转后缀,再计算。中间处理用栈操作
讲解看http://blog.csdn.net/antineutrino/article/details/6763722
这题是简易版本的,不用处理括号
#include <iostream> #include <cstdio> #include <cstring> #include <stack> using namespace std; int cmp(char a, char b) { if((a == ‘*‘ || a == ‘/‘) && (b == ‘+‘ || b == ‘-‘)) return 1; return 0; } double cal(double a, double b, char c) { if(c == ‘+‘) return a + b; if(c == ‘-‘) return a - b; if(c == ‘*‘) return a * b; if(c == ‘/‘) return a / b; } int main() { double a; while(~scanf("%lf", &a)) { char c; c = getchar(); stack <char> s1; stack <double> s2; if(!a && c==‘\n‘) break; s2.push(a); c = getchar(); while(~scanf("%lf", &a)) { if(s1.empty()) { s1.push(c); } else { if(cmp(c, s1.top())) s1.push(c); else { while(1) { double t1 = s2.top(); s2.pop(); double t2 = s2.top(); s2.pop(); char t3 = s1.top(); s1.pop(); double t4 = cal(t2, t1, t3); s2.push(t4); if(s1.empty() || cmp(c, s1.top())) { s1.push(c); break; } } } } s2.push(a); if(getchar() == ‘\n‘) break; c = getchar(); } while(!s1.empty()) { double t1 = s2.top(); s2.pop(); double t2 = s2.top(); s2.pop(); char t3 = s1.top(); s1.pop(); double t4 = cal(t2, t1, t3); s2.push(t4); } printf("%.2lf\n", s2.top()); } return 0; }
时间: 2024-11-06 18:15:04