算术表达式的求解-数据结构课程设计报告

余年寄山水
723次浏览
2021年01月30日 12:51
最佳经验
本文由作者推荐

-

2021年1月30日发(作者:美容美发店)
课程设计报告

题目:算术表达式求值

一、需求分析

1
、设计要求:

给定一个算术表达式,通过程序求出最后的结果

1>
、从键盘输入要求解的算术表达式;

2>
、采用栈结构进行算术表达式的求解过程;

3>
、能够判断算术表达式正确与否;

4>
、对于错误表达式给出提示;

5>
、对于正确的表达式给出最后的结果;

2
、设计构想:

为了实现算符优先算法使用两个工作栈,一个称作
OPTR
,以寄存运算符;
另一个称作
OPND
,用以寄存操作数或运算结果 。在操作数和操作符入栈前,通
过一个函数来判别,输入的是操作数还是操作符,操作数入
OP ND
,操作符入
OPTR
。在输入表达式的最后输入‘#’,设定‘
#
’的优先级最低,代表表达式
输入结束。在表达式输入过程中,遇操作数则直接入栈,遇到运算符则与 栈顶
运算符比较优先级
,
若当前运算符优先级高,
则当前运算符入栈
,
扫描下一符号
;
否则栈顶运算符出栈
,
两操作数出栈
,< br>进行运算
,
所得结果入数栈
,
重新比较当前
运算符与新栈顶运 算符

如此重复直到栈顶运算符与当前符号均为‘#’

运算
结束。

二、概要设计

1
、本程序包含的模块:


1
)栈模块——实现栈抽象数据类型


2
)运算模块——实现数据表达式的运算


3
)主程序模块

算术运算式的求解











mai
n






























































三、详细设计


1
)栈模块

1
、定义栈结构

struct Sqstack
{
elemtype *top;
//
栈顶元素

elemtype *base;
//
栈底元素

int stacksize;
//
栈的大小


};
2
、栈的基本操作

①初始化栈

status initstack(struct Sqstack &s)
{
=(elemtype *)malloc(stack_size*sizeof(elemtype));
if(!)
return OVERFLOW;
=;
ize=stack_size;
return OK;
}
②入栈

status push(struct Sqstack &s,elemtype e)
{
if(>=ize)
{
=(elemtype*)realloc(,(iz e+stack_increase
ment)*sizeof(elemtype));
if(!())
return OVERFLOW;
=+ize;
ize+=stack_increasement;
}
* ++=e;
return OK;
}
③出栈

elemtype pop(struct Sqstack &s)
{
elemtype e;
if(= =)
return ERROR;
e=*--;
return e;
}
④取栈顶元素

elemtype gettop(struct Sqstack &s)
{
elemtype e;
if(==)
return ERROR;
e=*(-1);
return e;
}

2
)运算模块

1< br>、判断输入字符
c
是否为操作符:若是,则返回
1
;否则,返回
0
int In(int c)
{
char p[10]=
int i=0;
while(p[i]!='0')
{
if(p[i]==c)
return 1;
i++;
}
return 0;
}
2
、判断运算符的优先级

char precede(char top,char c)
//
该函数为判断当前运算符与前一个运算符的优先级
,< br>前一个运算符高于或等于
当前运算符的优先级则返回‘>’


前一个 运算符小于当前运算符的优先级则返
‘<’,当前一个运算符为‘(’当前运算符为‘)’时返回‘=’ ,用于去除表
达式的括号。

{
char result;
switch(c)
{
case '#': result='>'; break;
case '+':
case '-':
if(top=='#'||top=='(')
result='<';
else
result='>'; break;
case '*':
case '/':
if(top=='*'||top=='/'||top=='^')
result='>';
else
result='<'; break;
case '%':






if(top=='%'||top=='/'||top=='^'||top=='*')
result='>';
else
result='<';break;
case ')':
if(top=='(')
result='=';
else
result='>'; break;
case '(': result='<'; break;
case '^': result='<'; break;
default: printf(
操作符输入错误!
n
}
return result;
}
3
、运算函数



基础运算函数:

实现相应的加、减、乘、除、乘方及带小括号的基本数学运算并返回 结果,
其中
a

b
为两个操作数,
theta
为操 作符

elemtype operate(elemtype a,char theta,elemtype b)
{
elemtype result;
switch(theta)
{
case '+': result=a+b; break;
case '-': result=a-b; break;
case '*': result=a*b; break;
case '/':

-


-


-


-


-


-


-


-