九度oj1019简单计算器

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值