HDOJ1237
来源:互联网 发布:戏曲 知乎 编辑:程序博客网 时间:2024/06/05 08:29
题目:http://acm.hdu.edu.cn/showproblem.php?pid=1237
题目描述:该题要求模拟实现计算器的加减乘除功能.
解题思路:运算符有优先级高低之分,借助栈将表达式(中缀表达式)转化为后缀表达式存于队列中,接着再次借助栈实现加减乘除功能.
- #include <iostream>
- #include <stack>
- #include <queue>
- #include <string>
- using namespace std;
- bool IsLowPriority(const string &s,const string &q)//the first parameter is in the stack to be compared
- {
- if(s=="*" || s=="/")
- return true;
- if((s=="+" || s=="-") && (q=="+" || q=="-"))
- return true;
- return false;
- }
- double GetNum(const string &n)
- {
- int len,cnt;
- double num;
- len=n.length();
- cnt=1;
- num=0;
- for(int i=len-1;i>=0;i--)
- {
- num += (n[i]-'0')*cnt;
- cnt *= 10;
- }
- return num;
- }
- int main()
- {
- int i;
- int len;
- double temp1,temp2,tempRes;
- string temp;
- char str[200];
- stack<string> s;
- stack<double> dStack;
- queue<string> q;
- while(gets(str))
- {
- if(!strcmp(str,"0"))
- break;
- while(!s.empty())
- s.pop();
- while(!q.empty())
- q.pop();
- while(!dStack.empty())
- dStack.pop();
- len=strlen(str);;
- temp="";
- /************infix to postfix conversion*******************/
- for(i=0;i<len;i++)
- {
- if(str[i] != ' ')
- {
- temp += str[i];
- }
- else
- {
- if(temp=="+" || temp=="-" || temp=="*" || temp=="/")
- {
- if(s.empty())
- s.push(temp);
- else
- {
- while(!s.empty() && IsLowPriority(s.top(),temp))
- {
- q.push(s.top());
- s.pop();
- }
- s.push(temp);
- }
- }
- else
- {
- q.push(temp);
- }
- temp="";
- }
- }
- if(temp != "")
- q.push(temp);
- while(!s.empty())
- {
- q.push(s.top());
- s.pop();
- }
- /********************compute**********************/
- while(!q.empty())
- {
- if(q.front()=="+" || q.front()=="-" || q.front()=="*" || q.front()=="/")
- {
- temp2=dStack.top();
- dStack.pop();
- temp1=dStack.top();
- dStack.pop();
- if(q.front()=="+")
- tempRes=temp1+temp2;
- if(q.front()=="-")
- tempRes=temp1-temp2;
- if(q.front()=="*")
- tempRes=temp1*temp2;
- if(q.front()=="/")
- tempRes=temp1/temp2;
- dStack.push(tempRes);
- q.pop();
- }
- else
- {
- dStack.push(GetNum(q.front()));
- q.pop();
- }
- }
- printf("%.2f/n",dStack.top());
- }
- return 0;
- }