NYOJ 35 表达式求值(栈的压入与弹出)

来源:互联网 发布:淘宝突然没有访客了 编辑:程序博客网 时间:2024/06/06 06:54

表达式求值

时间限制:3000 ms  |  内存限制:65535 KB
难度:4
描述
ACM队的mdd想做一个计算器,但是,他要做的不仅仅是一计算一个A+B的计算器,他想实现随便输入一个表达式都能求出它的值的计算器,现在请你帮助他来实现这个计算器吧。
比如输入:“1+2/4=”,程序就输出1.50(结果保留两位小数)
输入
第一行输入一个整数n,共有n组测试数据(n<10)。
每组测试数据只有一行,是一个长度不超过1000的字符串,表示这个运算式,每个运算式都是以“=”结束。这个表达式里只包含+-*/与小括号这几种符号。其中小括号可以嵌套使用。数据保证输入的操作数中不会出现负数。
数据保证除数不会为0
输出
每组都输出该组运算式的运算结果,输出结果保留两位小数。
样例输入
21.000+2/4=((1+2)*5+1)/4=
样例输出
1.504.00
解题思路:此题主要利用的是数据结构中栈的压入与弹出,把运算符和数据分别压入不同的栈中进行相应的操作,具体思路请看代码详解。
具体代码:#include <stdio.h>#include <stdlib.h>#include <string.h>#include <math.h>#include <stack>using namespace std;stack<char> osta;//定义一个char类型的字符栈stack<double> dsta;//定义一个double类型的数据栈int main(){int T;scanf("%d",&T);while(T--){char s[1010];scanf("%s",&s[1]);//从下标1开始读入int len=strlen(&s[1]);s[0]='(';s[len]=')';//把读入的表达式左端用“(”括起来,右端的等号换成“)”for(int i=0;i<=len;i++){if(s[i]=='(')osta.push(s[i]);//是左括号则压入字符栈中else if(s[i]>='0'&&s[i]<='9'){int b,K=0;double v=0;while(s[i]>='0'&&s[i]<='9'||s[i]=='.'){if(s[i]=='.')//判断是否是小数点{b=i;//记录小数点的位置K=1;//标记}elsev=v*10+s[i]-'0';i++;}i--;if(K==1)dsta.push(v/pow(10,i-b));elsedsta.push(v);}else if(s[i]=='+'||s[i]=='-'){while(osta.top()!='(')//判断栈顶元素,同下{double a=dsta.top();dsta.pop();double b=dsta.top();dsta.pop();double c;switch(osta.top()){case '+':c=b+a;break;case '-':c=b-a;break;case '*':c=b*a;break;case '/':c=b/a;break; }dsta.push(c);osta.pop();}osta.push(s[i]);}else if(s[i]=='*'||s[i]=='/'){if(osta.top()=='*'){double a=dsta.top();dsta.pop();double b=dsta.top();dsta.pop();dsta.push(b*a);osta.pop();}else if(osta.top()=='/'){double a=dsta.top();dsta.pop();double b=dsta.top();dsta.pop();dsta.push(b/a);osta.pop();}osta.push(s[i]);}else if(s[i]==')'){while(osta.top()!='('){double a=dsta.top();dsta.pop();double b=dsta.top();dsta.pop();double c;switch(osta.top()){case '+':c=b+a;break;case '-':c=b-a;break;case '*':c=b*a;break;case '/':c=b/a;break;}dsta.push(c);osta.pop();}osta.pop();}}printf("%.2lf\n",dsta.top());dsta.pop();//弹出最后数据,以免影响下一次运算}return 0;}


0 0
原创粉丝点击