#include<stack>
#include<stdio.h>
using namespace std;
char str[220];//保存表达式字符串
int mat[][5]={//优先级矩阵,若mat[i][j] ==1,则表示i号运算符优先级大于j号运算符
//运算符编码规则为+为1号,-为2号,*为3号,/为4号,人为添加在表达式首尾的标记运算符为0号
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
};
//bool compare(char a,char b){//a为当前碰到运算符b为栈顶运算符
// if(b=='#') return true;
// else if(b=='+' || b=='-'){
// if(a=='#' || a=='+' || a=='-') return false;
// else return true;
// }
// else return false;
//}
//# 4 + 2 * 5 - 7 / 11
//# 4 + 10 - 7 / 11
//# 14 - 7 / 11
//# 14 - 7 / 11 #
//# 14 - 7/11 #
//# x #
stack<int> op;//运算符栈,保存运算符编号
stack<double> in;//数字栈,运算结果可能存在浮点数,所以保存元素为double
void getOp(bool &reto,int &retn,int &i){//获得表达式中下一个元素函数,若函数运行结束时
//引用变量reto为true,则表示该元素为下一个运算符,其编号保存在引用变量retn中,否则
//该元素为一个数字,其值保存在引用变量retn中,引用变量i表示遍历到的字符串的下标
if(i==0 && op.empty()){//若此时遍历字符串第一个字符且运算符栈为空,我们人为
//添加编号为0的标记字符
reto=true;//为运算符
retn=0;//编号为0的标记字符
return;//返回
}
if(str[i]==0){//若此时遍历字符为空字符,则表示字符串已经被遍历完
reto=true;//返回为运算符
retn=0;//编号为0的标记字符
return;
}
// printf("断点1\n");
// return;
if(str[i]>='0'&&str[i]<='9'){//若当前字符为数字
reto=false;//返回为数字
retn = 0;
for(;str[i] && str[i]!=' ';++i)
retn=retn*10+str[i]-'0'; //1234
if(str[i])
i += 2;
}
else{//否则
reto=true;//返回为运算符
switch(str[i]){
case '+':retn=1;break;
case '-':retn=2;break;
case '*':retn=3;break;
case '/':retn=4;break;
}
i += 2;
}
}
int main(){
while(gets(str)){
if(str[0]=='0' && str[1]==0) break;
bool reto;
int retn;
int idx=0;
// printf("断点2\n");
// return 0;
while(!op.empty()) op.pop();
while(!in.empty()) in.pop();
// printf("断点3\n");
// return 0;
while(!(op.size()==2 && op.top()==0)){
// printf("断点4\n");
//return 0;
getOp(reto,retn,idx);
if(reto){
if(op.empty() || mat[retn][op.top()]){
op.push(retn);
}
else{
while(mat[retn][op.top()]==0){
double x=in.top();
in.pop();
printf("in栈长度:%d\n",in.size());
double y=in.top();
in.pop();
printf("断点5\n");
return 0;
double ans;
int oper=op.top();
op.pop();
//4 + 2 * 5 - 7 / 11
switch(oper){
case 1:ans=x+y;break;
case 2:ans=x-y;break;
case 3:ans=x*y;break;
case 4:ans=x/y;break;
}
in.push(ans);
}
op.push(retn);
}
}
else{
in.push((double)retn);
}
}
printf("%.2f\n",in.top());
}
return 0;
}
九度oj1019简单计算器
最新推荐文章于 2022-03-11 14:28:34 发布