浙江大学城市学院实验报告
课程名称数据结构与算法
实验项目名称实验四栈的应用---算术表达式的计算
学生姓名专业班级学号
实验成绩指导老师(签名)日期
一.实验目的和要求
1.进一步掌握栈的基本操作的实现。
2.掌握栈在算术表达式的计算方面的应用。
二. 实验内容
1.编写程序对后缀表达式进行求值(利用栈),即从键盘输入任一个后缀表达式,输出该后缀表达式的值。
要求:把栈的基本操作的实现函数存放在文件stack.h中,在主程序文件test4.cpp中包含后缀表达式求值函数double Compute(char *str)与主函数。
2.填写实验报告,实验报告文件取名为report4.doc。
3.上传实验报告文件report4.doc与源程序文件stack.h及test4.cpp到Ftp服务器上你自己的文件夹下。
三. 函数的功能说明及算法思路
包括每个函数的功能说明,及一些重要函数的算法实现思路
四. 实验结果与分析
包括运行结果截图等
五. 心得体会
记录实验感受、上机过程中遇到的困难及解决办法、遗留的问题、意见和建议等。
看着书写,问题不大。
自己写可能会漏写一些情况。
【附录----源程序】
Test4.cpp
#include<iostream.h>
#include<stdlib.h>
#include"stack.h"
double Compute(char *str){
Stack S;
InitStack(S);
double x,y;
int i = 0;
while(str[i]){
if(str[i] == ' '){
i++;
continue;
}
switch(str[i]){
case'+':
x = Pop(S) + Pop(S);
i++;
break;
case'-':
x = Pop(S);
x = Pop(S) - x;
i++;
break;
case'*':
x = Pop(S) * Pop(S);
i++;
break;
case'/':
x = Pop(S);
if(x != 0.0)
x = Pop(S)/x;
else{
cerr<<"Divide by 0!"<<endl;
exit(1);
}
i++;
break;
default:
x = 0;
while(str[i] >= 48 && str[i] <= 57){
x = x*10+str[i]-48;
i++;
}
if(str[i] == '.'){
i++;
y = 0;
double j = 10.0;
while(str[i] >= 48 && str[i] <= 57){
y = y + (str[i] - 48)/j;
i++;
j*=10;
}
x += y;
}
}
Push(S,x);
}
if(EmptyStack(S)){
cerr<<"Stack is empty"<<endl;
exit(1);
}
x = Pop(S);
if(EmptyStack(S))
return x;
else{
cerr<<"expression error!"<<endl;
exit(1);
}
ClearStack(S);
}
void main(){
char str[80];
cout<<"请输入算数表达式:";
cin.getline(str,sizeof(str));
cout<<"值为:"<<Compute(str)<<endl;
}
Stack.h
#define ElemType double
struct Stack{
ElemType *stack;
int top;
int Maxsize;
};
void InitStack(Stack& S){
S.Maxsize = 10;
S.stack = new ElemType[S.Maxsize];
if(!S.stack){
cerr<<"动态存储分配失败"<<endl;
exit(1);
}
S.top = -1;
}
void Push(Stack& S,ElemType item){
if(S.top == S.Maxsize-1){
int k = sizeof(ElemType);
S.stack = (ElemType*)realloc(S.stack,2*S.Maxsize*k);
S.Maxsize = 2*S.Maxsize;
}
S.top++;
S.stack[S.top] = item;
}
ElemType Pop(Stack& S){
if(S.top == -1){
cerr<<"Stack is empty!"<<endl;
exit(1);
}
S.top--;
return S.stack[S.top+1];
}
ElemType Peek(Stack& S){
if(S.top == -1){
cerr<<"Stack is empty!"<<endl;
exit(1);
}
return S.stack[S.top];
}
bool EmptyStack(Stack& S){
return S.top == -1;
}
void ClearStack(Stack& S){
if(S.stack){
delete []S.stack;
S.stack = 0;
}
S.top = -1;
S.Maxsize = 0;
}。