简单的表达式求值,A了好久,坑。
AC的代码:
#include <iostream> #include <cstdio> #include <cstring> #include <stack> using namespace std; int main() { char str, c; double a, b; stack <double> num; while(scanf("%lf", &a) != EOF) { while(!num.empty()) num.pop(); c = getchar(); if(c == '\n' && a == 0) break; num.push(a); scanf("%c", &c); while(scanf("%lf", &b)) { if(c == '*') //优先级高,取数,计算 { a = num.top(); num.pop(); num.push(a * b); } else if(c == '/') //同上 { a = num.top(); num.pop(); num.push(a / b); } else if(c == '+') //优先级低,先存入栈 num.push(b); else if(c == '-') //减法变成加上那个数的负 num.push(-b); c = getchar(); if(c == '\n') //结尾 break; scanf("%c", &c); getchar(); } double ans = 0.0; while(!num.empty()) { ans += num.top(); num.pop(); } printf("%.2lf\n", ans); } return 0; }
原文地址:http://blog.csdn.net/qq_25425023/article/details/45542577