http://acm.hdu.edu.cn/showproblem.php?pid=1237php
表達式計算,方法是中綴轉後綴,再計算。中間處理用棧操做ios
講解看http://blog.csdn.net/antineutrino/article/details/6763722ide
這題是簡易版本的,不用處理括號spa
#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; }