//2333;
#include <stdio.h> #include <ctype.h> #include <stack> using namespace std; #define MAXN 1000+10 char buf[MAXN]; stack<char> op ; //符号队列 ; stack<double> n ; //得到操作符的优先级 int getValue(char c) { if('(' == c) return 0; if('+'== c || '-'== c) return 1; if('*'== c|| '/'== c) return 2; } double calc(double a, double b, char c) { //printf("出栈操作: %f, %c, %f \n", a, c, b); switch(c) { case '+': return a+b; case '-': return a-b; case '*': return a*b; case '/': return a/b; } } //操作符出栈, 即进行一次计算 void pull() { double a, b; if(n.size()> 1 && !op.empty()) { b=n.top(); n.pop(); a=n.top(); n.pop(); n.push(calc(a, b, op.top())); //printf("%d: 出栈结果入栈!\n", n.size()); op.pop(); //printf("符号: %d 数字: %d 出栈完毕! \n", op.size(), n.size()); } } int main() { int N, i; double d; char c; scanf("%d", &N); while(N--) { scanf("%s", buf); i=0; while(1) { if(isalnum(buf[i])) { sscanf(buf+i, "%lf", &d); n.push(d); while(isalnum(buf[i]) || '.'== buf[i]) i++; } c=buf[i++]; if('=' == c || '\0' == c) break; if('('== c) { op.push(c); //printf("入栈\n"); } else if(')'== c) { while(!op.empty()) { if('('== op.top()){ op.pop(); break; } pull() ; } } else { //注意先后顺序, 不为空才能进行 op.top() 操作; while(!op.empty() && getValue(c) <= getValue(op.top())) pull(); op.push(c); //printf("%d: 符号入栈: %c \n", op.size(), c); } } while(!op.empty()) pull(); printf("%.2lf\n", n.top()); while(!n.empty()) n.pop(); } return 0; }
带空格, 无括号;
#include <stdio.h> int main(){ double s[200]; double num; while (scanf("%lf",&num)!=EOF){ int n=0; s[n++]=num; char c=getchar(); if (num==0&&c=='\n'){break;} char x; while(true){ scanf("%c %lf",&x,&num); switch(x){ case'+':s[n++]=num;break; case'-':s[n++]=-num;break; case'*':s[n-1]*=num;break; case'/':s[n-1]/=num;break;} if (getchar()=='\n'){break;}} double sum=0; for (int i=0;i<n;i++){sum +=s[i];} printf("%.2lf\n",sum);} return 0;}
浙公网安备 33010602011771号