计算该表达式值

/*
问题描述:输入一个只包含个位数字的简单四则运算表达式字符串,计算该表达式的值注
1、表达式只含+,-,*,/四则运算符,不含括号
2、表达式数值只包含个位整数(0-9),且不会出现0作为除数的情况
3、要考虑加减乘除按通常四则运算规定的计算优先级
4、除法用整数除法,即仅保留除法运算结果的整数部分。比如8/3=2。输入表达式保证无0作为除数情况发生
5、输入字符串一定是符合题意合法的表达式,其中只包括数字字符和四则运算符字符,
  除此之外不含其它任何字符,不会出现计算溢出情况
*/

int calculate(int len,char *expStr)
{
	char queue[128] = {'\0'};
	int head=0;
	int tail=0;
	char *str = expStr;
	int res,opt1,opt2;
	char buf,op,r[2];
#ifdef DEBUG
	printf("start\n");
#endif
	while(*str != '\0')
	{
#ifdef DEBUG
	printf("tail = %d,*str=%c\n",tail,*str);
#endif
		if(*str == '*')
		{

			tail--;
			buf = queue[tail];
			opt1 = buf - '\0';
			str++;
			buf = *str;
			opt2 = atoi(&buf);
			res = opt1*opt2;
			buf = '\0'+res;
			queue[tail] = buf;
			tail++;
			str++;
#ifdef DEBUG
	printf("* buf = %c\n",buf);
#endif
		}else if(*str == '/'){

			tail--;
			buf = queue[tail];
			opt1 = buf - '\0';
			str++;
			buf = *str;
			opt2 = atoi(&buf);
			res = opt1/opt2;
			buf = '\0'+res;
			queue[tail] = buf;
			tail++;
			str++;
#ifdef DEBUG
	printf("/ buf = %c\n",buf);
#endif
		}
		else if(*str == '+'||*str == '-'){
			queue[tail] = *str;
			tail++;
			str++;
		}else{
			buf = *str;
			res = atoi(&buf);
			buf = '\0'+res;
			queue[tail] = buf;
			tail++;
			str++;
		}
	}
#ifdef DEBUG
	printf("queue = %s,head = %d,tail = %d\n",queue,head,tail);
#endif
	res = 0;
	while(head < tail)
	{
		if(queue[head] == '+')
		{
			head++;
			buf = queue[head];
			opt1 = buf-'\0';
			res = res+opt1;
			head++;
		}else if(queue[head] == '-'){
			head++;
			buf = queue[head];
			opt1 = buf-'\0';
			res = res-opt1;
			head++;
		}
		else{
			buf = queue[head];
			res = buf - '\0';
			head++;
		}

	}
	return res;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值