栈计算表达式

题目描述:

对于一个不存在括号的表达式进行计算

输入:

存在多种数据,每组数据一行,表达式不存在空格

输出:

输出结果

样例输入:
6/2+3+3*4
样例输出:
18
本题表述很不清楚,通过AC代码可知,数据都是整数,并且一行可以有多个表达式,所以不能用gets(),getline()读入字符串。
本人写的代码,是利用栈的性质,来计算表达式的。
第二个代码,比较巧妙,参考大神写的。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stack>
#define MAX 100000
using namespace std;

bool isDigit(char c)
{
	if((c>='0' && c<='9') || c=='.')
		return true;
	return false;
}

bool cmpPri(char op1,char op2) //比较优先级, 当前面符号的优先级高时,返回true
{
	if( (op1=='*' || op1=='/')  && (op2=='+' || op2=='-' || op2=='#') )
		return true;
	else if((op1=='+' || op1=='-')  && (op2=='#') )
		return true;
	return false;
}

double op(double a,double b, char op)
{
	if(op=='+')
		return a+b;
	else if(op=='-')
		return a-b;
	else if(op=='*')
		return a*b;
	else if(op=='/')
		return (int)a*1.0/b;
	return 0;
}

void getOneTest(char *exp)
{
	stack<double>values;
	stack<char>signs;

	exp[strlen(exp)]='#'; //表达式末尾符号标记#
	exp[strlen(exp)+1]='\0';
	signs.push('#'); //初始化符号栈,符号标记#,优先级最低

	int i=0;
	if(exp[0]=='+' || exp[0]=='-' ) //如果表达式开头是‘+’或‘-’,添加数值0
		values.push(0);
	while(exp[i]!='\0')
	{
		if(isDigit(exp[i]))//是数字, 获得数值,入栈values
		{
			char temp[30];
			int j=0;
			while(exp[i]!='\0' && isDigit(exp[i]) )
				temp[j++]=exp[i++];
	       temp[j]='\0';
			values.push(atof(temp));
		}
		else //是符号
		{
			if( signs.empty() || cmpPri(exp[i],signs.top())) //exp[i]的优先级比栈顶的高
				signs.push(exp[i++]); //符号入栈signs
			else
			{//栈顶符号的优先级不低于exp[i]的优先级, 不能用cmpPri(signs.top() ,exp[i]),条件不一样
				while(!cmpPri(exp[i],signs.top()) && (exp[i]!='#' ||signs.top()!='#') ) //保证,符号都不是符号标记'#'
				{
					double a=values.top();
					values.pop();
					double b=values.top();
					values.pop();
					double c=op(b,a,signs.top());
					values.push(c);
					//printf("%.2f %c %.2f=%.2f\n",b,signs.top(),a,c);
					signs.pop();
				}
				signs.push(exp[i++]);
			}
		}
		if(signs.size()==2 && signs.top()=='#') //表达式遍历结束,只剩两个'#'符号标记
		{
			printf("%.0lf\n",values.top());
			break;
		}
	}
}

int main()
{
	char exp[MAX];
	while(scanf("%s",exp)!=EOF)  //不要用while(true)
		getOneTest(exp);
	return 0;
}

#include<stdio.h>
int a[100];
int main()
{
	int first;
	while(scanf("%d",&first)!=EOF)
	{
		int sum=0,i=0,j;
		a[i]=first;
		char c;
		while(scanf("%c",&c)!=EOF && (c=='+' || c=='-' || c=='*' ||  c=='/' ) )  //一定要加上!=EOF
		{
			int next;
			scanf("%d",&next);
			if(c=='+')
				a[++i]=next;
			else if(c=='-')
				a[++i]=-1*next;
			else if(c=='*')
				a[i]=a[i]*next;
			else
				a[i]=a[i]/next;
			//printf("%d\n",a[i]);
		}
		for(j=0;j<=i;j++)
			sum=sum+a[j];
		printf("%d\n",sum);
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值