关于堆栈的应用:后缀式四则运算编程代码,我只找到了一个完整的程序代码,但是我想把程序放到工程里运行

2025-03-06 19:59:13
推荐回答(2个)
回答1:

按你的要求 该成3个文件了
头文件h
#ifndef _XXXX_H
#define _XXXX_H
#define ERR -1
#define MAX 100 /*定义堆栈的大小*/
static int stack[MAX]; /*用一维数组定义堆栈*/
static int top=0; /*定义堆栈指示*/

int push(int i);
int pop();

#endif /* _XXXX_H */

函数文件cpp
#include "xxxx.h"

int push(int i) /*存储运算数,入栈操作*/
{
if(top {
stack[++top]=i; /*堆栈仍有空间,栈顶指示上移一个位置*/
return 0;
}
else
{
printf("The stack is full");
return ERR;
}
}
int pop() /*取出运算数,出栈操作*/
{
int var; /*定义待返回的栈顶元素*/
if(top!=NULL) /*堆栈中仍有元素*/
{
var=stack[top--]; /*堆栈指示下移一个位置*/
return var; /*返回栈顶元素*/
}
else
printf("The stack is empty!\n");
return ERR;
}

主文件cpp
#include
#include
#include
#include "xxxx.h"
void main()
{
int m,n;
char l;
int a,b,c;
int k;
do{
printf("\n\n\t请按以下提示输入你需要的信息\n");
printf("\n\t请你输入第二个运算数字:");
scanf("%d",&m);
push(m); /*第一个运算数入栈*/
printf("\n\t请你输入第二个运算数字:");
scanf("%d",&n);
push(n); /*第二个运算数入栈*/
printf("\n\t选择你要进行的运算操作(+/-/*//):");
l=getche(); /*输入运算符*/
switch(l) /*判定运算符,转而执行相应代码*/
{
case '+':
b=pop();
a=pop();
c=a+b;
printf("\n\n\t计算结果为: %d\n",c);
printf("\n");
break;
case '-':
b=pop();
a=pop();
c=a-b;
printf("\n\n\t计算结果为: %d\n",c);
printf("\n");
break;
case '*':
b=pop();
a=pop();
c=a*b;
printf("\n\n\t计算结果为: %d\n",c);
printf("\n");
break;
case '/':
b=pop();
a=pop();
c=a/b;
printf("\n\n\t计算结果为: %d\n",c);
printf("\n");
break;
}
printf("\t要继续输入计算吗?(Y/N):"); /*提示用户是否结束程序*/
l=getche();
if(l=='N')
exit(0);
}while(1);
}

回答2:

当发生中断或调用子程序时,PC值被保存到堆栈后,再被置入新的值(中断向量地址处的内容或调用的目的地址),