堆栈计算器实验报告.doc
文本预览下载声明
一、实验目的
本次实验为了学习用基本的数据结构解决实际应用中的问题,将学习的理论知识应用于实践,增强解决实际问题的能力。学会利用栈结构,按照算术运算优先级顺序,实现基本算术表达式的运算过程。
二、实验要求
功能要求:要求使用堆栈实现算术表达式的求值功能。
数据结构要求:使用两个工作栈,一个为OPTR,用于寄存运算符;另一个为OPND,用于寄存操作数和运算结构。
数据要求:输入:操作数栈的数据为整型,运算符栈的数据位字符型
输出:整型数据
三、设计实现
数据结构设计:
设置两个栈,一个为操作数栈opnd,一个为运算符栈optr。输入的表达式,遇到如果是操作数就压入到操作数堆栈中,如果是运算符就将优先级与当前堆栈运算符的优先级比较,谁的优先级数大就压入堆栈,否则将栈顶运算符弹出来进行运算。
程序流程设计:
定义链栈,判断运算符优先级,实现具体计算,错误处理、
算法流程:
主功能程序代码实现:
}#include stdafx.h
#include stdlib.h
#include math.h
#include string.h
#include conio.h
#include iostream.h
#include float.h
struct optr //存放操作符的栈
{
char * base;
char* top;
int size;
};
struct opnd //存放操作数的栈
{
int* base;
int* top;
int size;
};
void InitStack(struct optr* s)//申请操作符栈的空间及长度
{
s-base = (char*)malloc(100*sizeof(char));
s-top = s-base;
s-size =100;
}
void InitStack(struct opnd* s)//申请操作数栈的空间及长度
{
s-base = (int*)malloc(100*sizeof(int));
s-top = s-base;
s-size =100;
}
struct optr* Push(struct optr* stack , char opp)//插入操作符opp
{
*stack-top = opp;
stack-top++;
return stack;
}
struct opnd* Push(struct opnd* stack , int num , int i)
{
*stack-top = num;
stack-top++;
return stack;
}
char GetTop(struct optr* stack)//取栈顶元素
{
return *(stack-top-1);
}
int GetTop(struct opnd * stack) //取栈顶元素
{
return *(stack-top-1);
}
char PreCede(char oldChar , char newChar)
{
int oldInt;
int newInt;
switch (oldChar)
{
case +:
{
oldInt = 4;
break;
}
case -:
{
oldInt = 4;
break;
}
case *:
{
oldInt = 6;
break;
}
case /:
{
oldInt = 6;
break;
}
case (:
{
oldInt = 2;
break;
}
case ):
{
oldInt = 7;
break;
}
case =:
{
oldInt = 0;
break;
}
};
switch (newChar)
{
case +:
{
newInt = 3;
break;
}
case -:
{
newInt = 3;
break;
}
case *:
{
newInt = 5;
break;
}
case /:
{
newInt = 5;
break;
}
case (:
{
newInt = 7;
break;
}
case ):
{
newInt = 2;
break;
}
case =:
{
newInt = 0;
break;
}
};
if(oldInt n
显示全部