题目链接
http://ac.jobdu.com/problem.php?pid=1101
题目描述:
对于一个不存在括号的表达式进行计算
输入:
存在多种数据,每组数据一行,表达式不存在空格
输出:
输出结果
样例输入:
6/2+3+3*4
样例输出:
18
这道题我自己练习的时候显示的结果是对的,不知道为什么提交上去显示Runtime Error。
代码:
#include <stdio.h>
#include <stack>
using namespace std;
stack<int> op;
stack<double> in;
char str[10000];
int mat[][5]={
1,0,0,0,0, //#
1,0,0,0,0, //+
1,0,0,0,0, //-
1,1,1,0,0, //*
1,1,1,0,0, ///
};
void getOp(bool &isop,int &value,int &i){
if(i==0 && op.empty()==true){
isop=true;
value=0;
return;
}
if(str[i]==0){
isop=true;
value=0;
return;
}
if(str[i]>='0'&&str[i]<='9'){
isop=false;
}
else{
isop=true;
if(str[i]=='+'){
value=1;
}
else if(str[i]=='-'){
value=2;
}
else if(str[i]=='*'){
value=3;
}
else if(str[i]=='/'){
value=4;
}
i++;
return;
}
value=0;
for(;str[i]!=0 && str[i]>='0'&&str[i]<='9';i++){
value*=10;
value+=str[i]-'0';
}
if(str[i]!=0){
return;
}
}
int main(){
while(gets(str)){
while(op.empty()==false) op.pop();
while(in.empty()==false) in.pop(); // 清空栈
int i=0;
int idx=0;
int retnum;
bool retop;
while(true){
getOp(retop,retnum,idx);
if(retop==false){
in.push((double)retnum);
}
else{
double tmp;
if(op.empty()==true || mat[retnum][op.top()]==1){
op.push(retnum);
}
else{
while(mat[retnum][op.top()]==0){
int ret=op.top();
op.pop();
double b=in.top();
in.pop();
double a=in.top();
in.pop();
if(ret==1) tmp=a+b;
else if(ret==2) tmp=a-b;
else if(ret==3) tmp=a*b;
else {
if(b!=0)
tmp=a/b;
if(b==0) return 0;
}
in.push(tmp);
}
op.push(retnum);
}
}
if(op.size()==2 && op.top()==0) break;
}
if(in.top()-(int)in.top()==0){
printf("%d\n",(int)in.top());
}
else{
printf("%.2f\n",in.top());
}
}
return 0;
}