编译原理 对于输入的任一算术表达式

来源:百度知道 编辑:UC知道 时间:2024/05/14 04:28:49
对于输入的任一算术表达式,试设计算法,求出其对应的三地址中间代码,三元式或四元式,假设表达式中的运算分量都是简单变量,运算符只有:+,-,*,/。
例如:输入a+b*c-d#(以#结束)
输出三元式1(*,b,c)
2(+,a,1)
3(-,2,d)
或输出四元式(*,b,c,t1)
(+,a,t1,t2)
(-,t2,d,t3)
三元式与四元式只要一个就好。

#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<string.h>

#define DEBUG

#define NULL 0
#define ERROR -1
#define STACKSIZE 20

/* 定义字符类型栈 */
typedef struct{
char stackname[20];
char *base;
char *top;
} Stack;

/* ----------------- 全局变量--------------- */
Stack OPTR, OPND; /* 定义前个运算符栈,后个操作数栈 */
char expr[255] = ""; /* 存放表达式串 */
char *ptr = expr;
int step = 0; /* 计算的步次 */

int InitStack(Stack *s, char *name)
{
s->base=(char *)malloc(STACKSIZE*sizeof(char));
if(!s->base) exit (ERROR);
strcpy(s->stackname, name);
s->top=s->base;
return 1;
}

int In(char ch)
{
return(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='('||ch==')'||ch=='#');
}

void OutputStatus(vo