一 問題
題目描述
讀入一個只包含 +, -, *, / 的非負整數計算表達式,計算該表達式的值。
輸入
測試輸入包含若干測試用例,每個測試用例佔一行,每行不超過200個字符,整數和運算符之間用一個空格分隔。沒有非法表達式。當一行中只有0時輸入結束,相應的結果不要輸出。
輸出
對每個測試用例輸出1行,即該表達式的值,精確到小數點後2位。
樣例輸入
30 / 90 - 26 + 97 - 5 - 6 - 13 / 88 * 6 + 51 / 29 + 79 * 87 + 57 * 92
0
樣例輸出
12178.21
二 問題分析
這是很常見的問題,對應於數據結構的棧與隊列。 首先應當將中序表達式,轉化爲後綴表達式。然後利用站計算。
三 具體代碼
#include<iostream>
#include<string>
#include<cstdio>
#include<stack>
#include<queue>
#include<map>
using namespace std;
struct node
{
double num;
char op;
bool flag;
};
string str;
stack<node> s;
queue<node> q;
map<char,int> op;
vector<double> result;
void change();
void cal();
void display_queue();
void display_stack();
int main()
{
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
op['+']=op['-']=1;
op['*']=op['/']=2;
while(1)
{
getline(cin,str);
if(str=="0")
{
break;
}
for(string::iterator it=str.end(); it!=str.begin();it--)
{
if((*it)==' ')
{
str.erase(it);
}
}
cout<<str<<endl;
change();
cal();
while(!s.empty()) s.pop();
while(!q.empty()) q.pop();
}
for(vector <double>::iterator it=result.begin(); it!=result.end(); it++)
{
cout<<*it<<endl;
}
return 0;
}
void change()
{
double num;
node temp;
string tp="";
string::iterator it=str.begin();
while(it!=str.end())
{
double num;
if(*it>='0'&&*it<='9')
{
while(it!=str.end()&&*it>='0'&&*it<='9')
{
tp=tp+*it;
it++;
}
sscanf(tp.data(),"%lf",&num);
cout<<"num="<<num<<endl;
temp.flag=true;
temp.num=num;
q.push(temp);
tp="";
}
else
{
if(s.empty()||op[*it]>op[s.top().op])
{
temp.flag=false;
temp.op=*it;
s.push(temp);
}else
{
while(!s.empty()&&op[*it]<=op[s.top().op])
{
q.push(s.top());
s.pop();
}
temp.flag=false;
temp.op=*it;
s.push(temp);
}
it++;
}
}
while(!s.empty())
{
q.push(s.top());
s.pop();
}
display_queue();
display_stack();
}
void display_queue()
{
queue<node> temp=q;
cout<<"+++++++++++++q"<<endl;
while(!temp.empty())
{
cout<<temp.front().flag<<endl;
if(temp.front().flag)
{
cout<<temp.front().num<<endl;
}else
{
cout<<temp.front().op<<endl;
}
cout<<"--------------"<<endl;
temp.pop();
}
}
void display_stack()
{
stack<node> temp=s;
cout<<"+++++++++++++s"<<endl;
while(!temp.empty())
{
cout<<temp.top().flag<<endl;
if(temp.top().flag)
{
cout<<temp.top().num<<endl;
}else
{
cout<<temp.top().op<<endl;
}
cout<<"--------------"<<endl;
temp.pop();
}
}
void cal()
{
while(!q.empty())
{
if(q.front().flag)
{
if(!q.empty())
{
s.push(q.front());
q.pop();
}
}
else
{
node temp;
char ch=q.front().op;
if(!q.empty())
{
q.pop();
}
double temp1,temp2;
if(!s.empty())
{
temp1=s.top().num;
s.pop();
}
if(!s.empty())
{
temp2=s.top().num;
s.pop();;
}
temp.flag=true;
if(ch=='+')
{
temp.num=temp2+temp1;
}
if(ch=='-')
{
temp.num=temp2-temp1;
}
if(ch=='*')
{
temp.num=temp2*temp1;
}
if(ch=='/')
{
temp.num=temp2/temp1;
}
s.push(temp);
}
display_queue();
display_stack();
}
result.push_back(s.top().num);
}
四 運行結果
測試用例
結果