用栈实现四则运算计算器 implement a calculator using stack

int Operate(int x,char opr,int y)   //计算
{
	int result; 
	switch (opr) 
	{ 
		case '+': 
			result = x + y; 
			break; 
		case '-': 
			result = x - y; 
			break;
		case '*': 
			result = x * y; 
			break;
		case '/': 
			result = x / y; 
			break;
	}
	return result;
}

char Precede(char s,char c) //判断字符的优先级 
{
	switch(s)
	{
		case '+':
		case '-':
		{
			if(c=='+'||c=='-')
				return '<';
		    else if (c=='*'||c=='/')
				return '<';
		    else if(c=='(') 
				return '<'; 
		    else if(c==')') 
				return '>'; 
		    else 
				return '>';
		}
		break;

		case '*':
		case '/':
		{
			if(c=='+'||c=='-')
				return '>';
			else if (c=='*'||c=='/')
				return '<';
			else if(c=='(') 
				return '<'; 
			else if(c==')') 
				return '>'; 
			else 
			return '>'; 
		}
		break;

		case '(':
		{
			if(c==')')
				return '=';
			else 
				return '<';
		}
		break;

		case ')':
		{
		   return '>';
		}
		break;


		case '#':
		{
			if(c=='#')
				return '=';
			else
				return '<';
		}
		break;
	}
}

int main ()
{
  stack  operands;
  stack  operators;
  float left, right;
  float num;
  char ope;
  scanf("%f",&num);
  operands.push(num);
  scanf("%c",&ope);
  operators.push(ope);
 
  while(1)
  {
	scanf("%f",&num);
	operands.push(num);
	
	scanf("%c",&ope);
	
	while(!operators.empty())
	{
		if('<' == Precede(ope,operators.top())|| '=' == ope)
		{
			right = operands.top();
			operands.pop();
			left = operands.top();
			operands.pop();
			operands.push(Operate(left,operators.top(),right));
			cout << left << " " << operators.top() << " " << right << endl;
			operators.pop();
		}
		else
		break;
	}
	if('=' == ope)
	{
		cout << operands.top()<

暂时未包含括号处理。

你可能感兴趣的:(Coding,Interview)