Expression

来源:互联网 发布:山东兆物网络李民 编辑:程序博客网 时间:2024/06/06 15:42
//while (从exp读取字符ch,ch!='\0')//{    若ch为数字,将后续的所有数字均依次存放到postexp中,并以字符“#”标志数值串结束。//若ch为左括号“(”,则将此括号进栈到运算符栈op中。//               若ch为右括号“)”,则将运算符栈op中左括号“(”以前的运算符依次出栈并存放到postexp中,然后将左括号“(”删除。//               若ch运算符优先级小于或等于op栈顶运算符的优先级 (除栈顶运算符为“(”外)的优先级,则依次出栈并存入到postexp中,然后将ch进栈。//}//若字符串exp扫描完毕,则将运算栈op中的所有运算符依次出栈并存放到postexp中。最后得到后缀表达式postexp。
#include <stdlib.h>float ComputeValue(const char postExp[]){struct{doubledata[20];inttop;} St;St.top = -1;int index = 0;char ch = postExp[index];while (ch != '\0'){double tmp = 0.0;switch (ch){case '+':St.data[St.top - 1] = St.data[St.top - 1] + St.data[St.top];--St.top;break;case '-':St.data[St.top - 1] = St.data[St.top - 1] - St.data[St.top];--St.top;break;case '/':if (St.data[St.top] != 0){St.data[St.top - 1] = St.data[St.top - 1] / St.data[St.top];--St.top;}else{exit(0);}break;default:double d = 0.0;while (ch <= '9' && ch >= '0'){d = 10 * d + ch - '0';++index;ch = postExp[index];}++St.top;St.data[St.top] = d;break;}++index;ch = postExp[index];}return St.data[St.top];}void Trans(const char exp[], char postExp[]){struct  {chardata[50];inttop;} Op;Op.top = -1;int expIndex = 0, index = 0;char ch = exp[expIndex];while (ch != '\0'){switch (ch){case '(':++Op.top; Op.data[Op.top] = ch;break;case ')':while(Op.data[Op.top] != '('){postExp[index] = Op.data[Op.top];++index;--Op.top;}--Op.top;break;case '+': case '-':while(Op.top != -1 && Op.data[Op.top] != '(') // zui di you xian ji{postExp[index] = Op.data[Op.top];++index;--Op.top;}++Op.top;Op.data[Op.top] = ch;break;case '*': case '/':while (Op.data[Op.top] == '*' || Op.data[Op.top] == '/') // 最高优先级{postExp[index] = Op.data[Op.top];++index;--Op.top;}++Op.top;Op.data[Op.top] = ch;break;case ' ':break;default:while (ch <= '9' && ch >= '0'){postExp[index] = ch;++index;++expIndex;ch = exp[expIndex];}--expIndex; postExp[index] = '#';++index;break;}++expIndex;ch = exp[expIndex];}while (Op.top != -1){postExp[index] = Op.data[Op.top];++index; --Op.top;}}int main(){char exp[50] = "(56-20)/(4+2)";char postExp[50] = "";Trans(exp, postExp);char test[50] = "56#20#-4#2#+/";ComputeValue(test);return 0;}

 
	
				
		
原创粉丝点击