中缀表达式的计算(含出错处理,括号处理)

以下是一个中缀表达式计算的程序,大体思路是利用两个栈,一个存放操作数,另外一个存放运算符,分别将输入的操作数和运算符存入其中,若输入的运算符优先级小于栈顶的运算符,则将栈顶的运算符取出,并将操作数栈的两个栈顶操作数取出进行运算,将运算结果重新填入栈中,而后将刚才输入的运算符压入运算符栈中。重复上述过程,直到运算符栈的有效运算符为空。

为了区别不同运算符的优先性,我将+-*/的优先级的代号分别设为1、2、4、5。通过比较输入的优先级是否比栈顶的优先级小2及以上来看出输入的优先级是否小于栈顶的优先级。这样既可以唯一表示这四个运算符,也可以保证各自的优先级和运算顺序。  


对于括号,我将待压入栈的左括号的优先级置为最高,这样可以保证左括号可以直接压入栈。


我还使用了表达式的输入错误处理,包括除数为0,括号不配对。

#include <iostream>
#include <stack>
#include <cmath>
#include <string>
using namespace std;

int main()
{
	cout<<"Enter some infix expression,such as 1+1(must be integers,Ctrl+z to end):"
		<<endl;

start:	string line; //使用标号语句和跳转语句,当输入的表达式非法时可以便捷地跳回到此处,
						//重新输入数据
	while(getline(cin,line))
	{
		stack<double> numStack;
		stack<int> expStack;

		expStack.push(-2); 

		string s="";
		int prop=0,first=0,num=0; //prop表示运算符的优先级
		double val1=0.0,val2=0.0,result=0.0;
		char ch;
	
		//getline(cin,line);
		line+='#'; //自己设置停止时刻
		for(int i=0;line[i]!='#';++i)
		{
			ch=line[i];

			if(isdigit(ch))
				s+=ch;
			else
			{
				//当s不为空时才进行转换
				if(s!="")
				{
					num=atoi(s.c_str());
					numStack.push(num);
					s=""; //将s清空
				}

				if(ch==')')
				{
					while(expStack.top()!=-2&&expStack.top()!=-7) //还没到栈底,并且不是左括号时
					{
						first=expStack.top();
						expStack.pop();
		
						val1=numStack.top();
						numStack.pop();
						val2=numStack.top();
						numStack.pop();

						switch(first)
						{
		
						case 1:
							result=val2+val1;
							break;
						case 2:
							result=val2-val1;
							break;
						case 4:
							result=val2*val1;
							break;
						case 5:
							//当输入除数为0时可能存入val1的不为0,可能很接近0,只要val1足够接近0就认为是0
							if(val1<0.0000001)
							{
								cerr<<"The divider can't be 0! input again:"<<endl;
								//exit(1);
								goto start;
							}
							result=val2/val1;
							break;
						}
						numStack.push(result);
					}

					//将左括号删去
					if(expStack.top()==-7)
						expStack.pop();
					else
					{
						cout<<"'(' and ')' can't match! input again:"<<endl;
						goto start;
						//exit(1);
					}
				}

				else
				{
					switch(ch)
					{
					case '+':
							prop=1;
							break;
					case '-':
							prop=2;
							break;
					case '*':
							prop=4;
							break;
					case '/':
							prop=5;
							break;
					case '(':
							prop=7; //左括号栈外的优先级最高,可直接入栈

					}
					first=expStack.top();

					//说明栈顶符号的优先级大于读入的优先级
					if(prop-first<2)
					{
						expStack.pop(); //除去运算符栈栈顶元素

						//取出两个操作数
						val1=numStack.top();
						numStack.pop();
						val2=numStack.top();
						numStack.pop();

						switch(first)
						{
						case 1:
							result=val2+val1;
							break;
						case 2:
							result=val2-val1;
							break;
						case 4:
							result=val2*val1;
							break;
						case 5:
							if(0==val1)
							{
								cerr<<"The divider can't be 0! input again:"<<endl;
								goto start;
								//exit(1);
							}
							result=val2/val1;
							break;
						}
						numStack.push(result); //将运算的结果重新压到操作数栈中
					}

					if(7==prop)
						expStack.push(-7); //-7是左括号的标志
					else
						expStack.push(prop); //将新来的运算符压入运算符栈
				}
			}	
		}

		//最后一个输入的操作数单独处理
		if(s!="")
		{
			num=atoi(s.c_str());
			numStack.push(num);
		}


		//到了expStack的栈顶

		while(expStack.top()!=-2)
		{
		
			first=expStack.top();

			//如果还剩左括号时,输出错误信息
			if(first==-7)
			{
				cout<<"'(' and ')' can't match! input again:"<<endl;
				goto start;
				//exit(1);
			}

			expStack.pop();
		
			val1=numStack.top();
			numStack.pop();
			val2=numStack.top();
			numStack.pop();

			switch(first)
			{
		
			case 1:
				result=val2+val1;
				break;
			case 2:
				result=val2-val1;
				break;
			case 4:
				result=val2*val1;
				break;
			case 5:
				if(val1<0.0000001)
				{
					cerr<<"The divider can't be 0! input again:"<<endl; //除数不能为0
					goto start;
					//exit(1);
				}
				result=val2/val1;
				break;
			}

			numStack.push(result);
		
		}

		cout<<"result:"<<numStack.top()<<endl;
	}

	return 0;
	

}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
中缀表达式转后缀表达式中括号处理可以通过栈来实现,具体步骤如下: 1. 初始化两个栈,一个用来存储操作符,一个用来存储后缀表达式。 2. 遍历中缀表达式的每一个字符,如果是数字,直接加入后缀表达式栈中;如果是左括号,将其压入操作符栈中;如果是右括号,则将操作符栈中的操作符依次弹出并加入后缀表达式栈中,直到遇到括号为止,并将左括号弹出丢弃。 3. 如果是操作符,则判断其与操作符栈顶元素的优先级,如果优先级低于等于栈顶元素,则将栈顶元素弹出并加入后缀表达式栈中,重复此步骤直到操作符栈为空或者栈顶元素的优先级小于当前操作符的优先级,最后将当前操作符压入操作符栈中。 4. 如果中缀表达式遍历完毕,则将操作符栈中的操作符依次弹出并加入后缀表达式栈中。 下面是一个示例 C 语言代码实现中缀表达式转后缀表达式: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define MAX_SIZE 100 // 定义栈结构 typedef struct { int top; char data[MAX_SIZE]; } Stack; // 初始化栈 void init(Stack *s) { s->top = -1; } // 判断栈是否为空 int is_empty(Stack *s) { return s->top == -1; } // 判断栈是否已满 int is_full(Stack *s) { return s->top == MAX_SIZE - 1; } // 入栈操作 void push(Stack *s, char c) { if (is_full(s)) { printf("Stack is full!\n"); exit(1); } s->data[++(s->top)] = c; } // 出栈操作 char pop(Stack *s) { if (is_empty(s)) { printf("Stack is empty!\n"); exit(1); } return s->data[(s->top)--]; } // 获取栈顶元素 char peek(Stack *s) { if (is_empty(s)) { printf("Stack is empty!\n"); exit(1); } return s->data[s->top]; } // 获取操作符优先级 int get_priority(char c) { switch (c) { case '+': case '-': return 1; case '*': case '/': return 2; case '(': case ')': return 0; default: return -1; } } // 中缀表达式转后缀表达式 void infix2postfix(char *infix, char *postfix) { Stack s; int i, j; init(&s); j = 0; for (i = 0; infix[i] != '\0'; i++) { if (isdigit(infix[i])) { postfix[j++] = infix[i]; } else if (infix[i] == '(') { push(&s, infix[i]); } else if (infix[i] == ')') { while (peek(&s) != '(') { postfix[j++] = pop(&s); } pop(&s); // 弹出左括号 } else { while (!is_empty(&s) && get_priority(peek(&s)) >= get_priority(infix[i])) { postfix[j++] = pop(&s); } push(&s, infix[i]); } } while (!is_empty(&s)) { postfix[j++] = pop(&s); } postfix[j] = '\0'; } int main() { char infix[MAX_SIZE]; char postfix[MAX_SIZE]; printf("Enter infix expression: "); fgets(infix, MAX_SIZE, stdin); infix2postfix(infix, postfix); printf("Postfix expression: %s\n", postfix); return 0; } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值