-
题目描述:
-
对于一个不存在括号的表达式进行计算
-
输入:
-
存在多种数据,每组数据一行,表达式不存在空格
-
输出:
-
输出结果
-
样例输入:
-
6/2+3+3*4
-
样例输出:
-
18
代码:
#include <stdio.h>
#include <stack>
using namespace std;
stack<double> in;
stack<int> op;
char str[100];
int p[][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 &retop, int &retnum, int &i) {
if(i==0 && op.empty()) {
retop = true;
retnum = 0;
return;
}
if(str[i]==0) {
retop = true;
retnum = 0;
return;
}
if(str[i]>='0' && str[i]<='9')
retop = false;
else {
retop = true;
if(str[i]=='+')
retnum = 1;
else if(str[i]=='-')
retnum = 2;
else if(str[i]=='*')
retnum = 3;
else
retnum = 4;
i++;
return;
}
retnum = 0;
while(str[i]>='0'&&str[i]<='9') {
retnum *= 10;
retnum += str[i] - '0';
i++;
}
return;
}
int main() {
while(gets(str)) {
bool retop;
int retnum;
int index = 0;
while(!in.empty()) in.pop();
while(!op.empty()) op.pop();
while(true) {
double tmp;
getOp(retop,retnum,index);
if(retop==false)
in.push((double)retnum);
else {
if(op.empty() || p[retnum][op.top()]==1)
op.push(retnum);
else {
while(p[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
tmp = a / b;
in.push(tmp);
}
op.push(retnum);
}
}
if(op.size()==2 && op.top()==0)
break;
}
int ans = (int) in.top();
printf("%d\n",ans);
}
return 0;
}
在自己机器上测试结果正确。但是提交时:Runtime Error.