nyoj 题目35 表达式求值

来源:互联网 发布:linux虚拟机home扩容 编辑:程序博客网 时间:2024/06/06 01:29

                                                                      表达式求值

时间限制: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
来源
数据结构课本例题改进
上传者
张云聪

解法:先求出后缀表达式(逆波兰式),然后计算(栈+stringstream)!

#include<bits/stdc++.h>using namespace std;string s,str;int yxj(char ch){    switch(ch)    {        case '+':        case '-':return 1;        case '*':        case '/':return 2;        default: return 0;    }}int main(){    int T;    cin>>T;    while(T--)    {        cin>>s;        stack<char>pq;        stack<double>qp;        pq.push('#');        int len=s.size(),i=0;        str.clear();        while(i<len-1)        {            if(s[i]=='(')            {                pq.push(s[i]);                i++;            }            else if(s[i]==')')            {                while(pq.top()!='(')                {                    str+=pq.top();                    pq.pop();                    str+=' ';                }                pq.pop();                i++;            }            else if(s[i]=='+'||s[i]=='-'||s[i]=='*'|s[i]=='/')            {                while(yxj(pq.top())>=yxj(s[i]))                {                    str+=pq.top();                    str+=' ';                    pq.pop();                }                pq.push(s[i]);                i++;            }            else            {                while(s[i]>='0'&&s[i]<='9'||s[i]=='.')                {                    str+=s[i];                    i++;                }                str+=' ';            }        }        while(pq.top()!='#')        {            str+=pq.top();            pq.pop();            str+=' ';        }        stringstream ss(str);        string buf;        while(ss>>buf)        {            if(isdigit(buf[0]))            {                char a[100];                double num;                int i=0;                for(i=0;i<buf.size();i++)                    a[i]=buf[i];                a[i]='\0';                num=atof(a);                qp.push(num);            }            else            {                double x=qp.top();                qp.pop();                double y=qp.top();                qp.pop();                if(buf=="+")                    qp.push(y+x);                else if(buf=="-")                    qp.push(y-x);                else if(buf=="*")                    qp.push(y*x);                else if(buf=="/")                    qp.push(y/x);            }        }        printf("%.2lf\n",qp.top());    }    return 0;}


 

0 0
原创粉丝点击