本文共 2552 字,大约阅读时间需要 8 分钟。
通过修改完善教材中的算法3.4,利用栈来实现算术表达式求值的算法。对算法3.4中调用的几个函数要给出其实现过程:
程序运行时,输入合法的算术表达式(中间值及最终结果要在0~9之间,可以包括加减乘除和括号),便可输出相应的计算结果。
void main() { printf("请输入算术表达式,并以#结束.\n"); printf("the result of expression is:%d\n",EvaluateExpression());} Status In(SElemType c) { // 判断c是否为运算符 switch(c) { case '+': return TRUE; case '-': return TRUE; case '*': return TRUE; case '/': return TRUE; case '(': return TRUE; case ')': return TRUE; case '#': return TRUE; default: return FALSE; }} SElemType Precede(SElemType t1,SElemType t2) { SElemType f; switch(t2) { case '+': if (t1=='('||t1=='#') f='<'; else f='>'; break; case '-': if (t1=='('||t1=='#') f='<'; else f='>'; break; case '*': if (t1=='+'||t1=='-'||t1=='('||t1=='#') f='<'; else f='>'; break; case '/': if (t1=='+'||t1=='-'||t1=='('||t1=='#') f='<'; else f='>'; break; case '(': if (t1=='+'||t1=='-'||t1=='('||t1=='#'||t1=='*'||t1=='/') f='<'; break; case ')': if (t1=='+'||t1=='-'||t1=='*'||t1=='/'||t1==')') f='>'; else if (t1=='(') f='='; break; case '#': if (t1=='#') f='='; else f='>'; break; default: cout<<"输入超出范围。。。"; } return f;} SElemType Operate(SElemType a,SElemType theta,SElemType b) { SElemType c; a=a-'0'; b=b-'0'; switch(theta) { case '+': c=a+b+'0';break; case '-': c=a-b+'0';break; case '*': c=a*b+'0';break; case '/': c=a/b+'0';break; } return c;} 通过上述程序的实现,可以输入如下的表达式:
123+456*789#
程序会输出:
the result of expression is:123456789
转载地址:http://weqfk.baihongyu.com/