简单的计算器(利用栈)

#include<stdio.h>
#include<string.h>
char judge[7][7]={'>','>','<','<','<','>','>',  //定义优先级 
            	  '>','>','<','<','<','>','>',
            	  '>','>','>','>','<','>','>',
            	  '>','>','>','>','<','>','>',
            	  '<','<','<','<','<','=',' ',
				  '>','>','>','>',' ','>','>',
            	  '<','<','<','<','<',' ','='};
char symble[7]={'+','-','*','/','(',')','#'};   //定义符号 
char symbleStack[100];
int numStack[100];
char *top,*base;
int *top1,*base1;
void pushSymble(char a){
	*top = a;
	top++;
}

void pushNum(int b){
	*top1 = b;
	top1++;
}

char popSymble(){
	if(base == top){
		return NULL;
	}
	top--;
	return *top;
}

int popNum(){
	if(base1 == top1){
		return NULL;
	}
	top1--;
	return *top1;
}

char ju(char x,char y){
	int f = 0 , g = 0;
	for(int i=0; i<7; i++){
		if(symble[i]==x){
			f=i;
		}
		if(symble[i]==y){
			g=i;
		}
	}
	return judge[f][g];
}

int Operate(int a,char sym,int b){
	switch(sym){
		case '+':{
			return a+b;
			break;
		}
		case '-':{
			return a-b;
			break;
		}
		case '*':{
			return a*b;
			break;
		}
		case '/':{
			return a/b;
			break;
		}
	}
}

int main(){
	top = base = symbleStack;
	top1 = base1 = numStack;
	pushSymble('#');
	printf("请输入表达式以#结束\n");
	char biaoDaShi[1000];
	scanf("%s",biaoDaShi);
	getchar();
	int i=0;
	while(biaoDaShi[i]!='#'||*(top-1)!='#'){
		if(biaoDaShi[i]>='0'&&biaoDaShi[i]<='9'){
			pushNum((biaoDaShi[i]-'0'));
			printf("!!!!!!!!数值%d\n",biaoDaShi[i]-'0');
			i++;
		}else{
			switch(ju(*(top-1),biaoDaShi[i])){
				case '<':{
					pushSymble(biaoDaShi[i]);
					printf("@@@@@@@@@符号%c\n",biaoDaShi[i]);
					i++;
					break;
				}
				case '=':{
					popSymble();
					printf("@@@@@@@@@符号%c\n",biaoDaShi[i]);
					i++;
					break;
				}
				case '>':{
					char tempSymble = popSymble();
					int tempNumB = popNum();
					int tempNumA = popNum();
					pushNum(Operate(tempNumA,tempSymble,tempNumB));
					printf("#########数值%d\n",*(top1-1));
					break;
				}
			}
		}
	}
	printf("%d\n",*(top1-1)); 
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值