标签:nyoj35
2 1.000+2/4= ((1+2)*5+1)/4=
1.50 4.00
//参考自《数据结构与算法分析P54》 #include <stdio.h> #define maxn 1000 char stack[maxn + 2], out[2 * maxn]; double ans[maxn]; int id1, id2, id3; char pop(){ return stack[--id1]; } void check(char ch){ char c; if(ch == ')'){ while((c = pop()) != '(') out[id2++] = c; }else if(ch == '*' || ch == '/'){ while(id1 && stack[id1-1] != '+' && stack[id1-1] != '-' && stack[id1-1] != '('){ out[id2++] = pop(); } }else if(ch == '+' || ch == '-'){ while(id1 && stack[id1-1] != '('){ out[id2++] = pop(); } } } void push(double a){ ans[id3++] = a; } int main(){ char ch; int b, t, sign; double a; scanf("%d", &t); while(t--){ getchar(); id1 = id2 = id3 = sign = 0; while((ch = getchar()) != '='){ if(ch >= '0' && ch <= '9' || ch == '.'){ if(sign == 1) out[id2++] = ' ', sign = 0; out[id2++] = ch; }else if(ch == '('){ stack[id1++] = ch; sign = 1; }else if(ch == ')'){ check(ch); sign = 1; }else{ check(ch); stack[id1++] = ch; sign = 1; } } while(id1) out[id2++] = pop(); //for(int i = 0; i < id2; ++i) putchar(out[i]); putchar('\n'); for(int i = 0; i < id2; ++i){ if(out[i] == ' ') continue; if(out[i] >= '0' && out[i] <= '9' || out[i] == '.'){ sscanf(out + i, "%lf%n", &a, &b); --i; i += b; push(a); }else if(out[i] == '+'){ ans[id3-2] += ans[id3-1]; --id3; }else if(out[i] == '-'){ ans[id3-2] -= ans[id3-1]; --id3; }else if(out[i] == '*'){ ans[id3-2] *= ans[id3-1]; --id3; }else if(out[i] == '/'){ ans[id3-2] /= ans[id3-1]; --id3; } } printf("%.2lf\n", ans[0]); } return 0; }
NYOJ35 表达式求值 【栈】,布布扣,bubuko.com
标签:nyoj35
原文地址:http://blog.csdn.net/chang_mu/article/details/26490181