问题遇到的现象和发生背景
将前缀表达式转换成后缀表达式,我的 houzhui(table t,table h)这个和jisuan(table h)这个函数出问题了,表达式输入#3+5#,转换成后缀为35,有错误,但是输入#3+5*(3+5)#结果就没有错误,然后jisuan(table h)这个函数的值一直是0,我不知道是什么原因
用代码块功能插入代码,请勿粘贴截图
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define STACK_INIT_SIZE 30
typedef char SElemType;
#define Size 30
typedef struct Table{
char *head;
int length;
int size;
}table;
//创建顺序表
table initTable(){
table t;
t.head=(char*)malloc(Size*sizeof(char));
t.length=0;
t.size=Size;
return t;
}
//输出
void displayTable(table t){
for(int i=0;i<t.length;i++){
printf("%c",t.head[i]);
}
printf("\n");
}
//输入
table shuru(table t){
char s;
int i=0;
scanf("%c",&s);
while (s!='\n'){
t.head[i]=s;
t.length++;
scanf("%c",&s);
i++;
}
return t;
}
typedef struct {
SElemType base[STACK_INIT_SIZE];
int top;
}sqstack;
void initStack(sqstack *S){
S->top=-1;
}
void Push(sqstack *S,char e){
if(S->top==STACK_INIT_SIZE-1){
printf("Stack is full");
}
else
S->base[++S->top]=e;
}
void Pop(sqstack *S,SElemType *e){
if(S->top==-1) printf("Stack is full");
else *e=S->base[S->top--];
}
void GetTop(sqstack *S,SElemType *e){
if(S->top==-1) printf("Stack is full");
else *e=S->base[S->top];
}
int zhuanhuan(char a){
int b;
if(a=='+'){
b=0;
return b;
}
if(a=='-'){
b=1;
return b;
}
if(a=='*'){
b=2;
return b;
}
if(a=='/'){
b=3;
return b;
}
if(a=='('){
b=4;
return b;
}
if(a==')'){
b=5;
return b;
}
if(a=='#'){
b=6;
return b;
}
}
int IN(char a){
int b;
if(a=='+'||a=='-'||a=='*'||a=='/'||a=='('||a==')'||a=='#'){
b=1;
return b;
}
else{
b=0;
return b;
}
}
char panduan(int a,int b){
char Prior[7][7]={'>','>','<','<','<','>','>',
'>','>','<','<','<','>','>',
'>','>','>','>','<','>','>',
'>','>','>','>','<','>','>',
'<','<','<','<','<','=',' ',
'>','>','>','>',' ','>','>',
'<','<','<','<','<',' ','='
};
return Prior[a][b];
}
table houzhui(table t,table h){
sqstack S;
initStack(&S);
int i=0,j=0;
Push(&S,t.head[i]);
i++;
char e,x;
GetTop(&S,&e);
while ((t.head[i]!='#'||e!='#')&&i<=t.length){
if(!IN(t.head[i])){
h.head[j++]=t.head[i++];
h.length++;
}
else{
GetTop(&S,&e);
switch (panduan(zhuanhuan(e), zhuanhuan(t.head[i]))) {
case '<':
Push(&S,t.head[i]);
i++;
break;
case '=':
Pop(&S,&x);
i++;
break;
case '>':
Pop(&S,&x);
h.head[j++]=x;
h.length++;
break;
}
}
}
return h;
}
float evaluate(char x, float op1, float op2)
{
if (x == '+')
return(op1 + op2);
if (x == '-')
return(op1 - op2);
if (x == '*')
return(op1 * op2);
if (x == '/')
{
if (op2 == 0)
{
return -9999;
}
else
{
return(op1 / op2);
}
}
}
float jisuan(table h){
sqstack S;
initStack(&S);
float e;
char a,b,x;
int j=0;
while (j<=h.length-1){
if(!IN(h.head[j])){
Push(&S,h.head[j]);
}
else{
Pop(&S,&b);
Pop(&S,&a);
x=h.head[j];
Push(&S,(char)evaluate(x,(float )(a-'0'),(float )(b-'0')));
}
j++;
}
Pop(&S,&e);
return e;
}
int main() {
table t=initTable();
table h=initTable();
t=shuru(t);
displayTable(houzhui(t,h));
printf("%f", jisuan(houzhui(t,h)));
return 0;
}
运行结果及报错内容
#3+5#
35
0.000000
#3+5*(3+5)#
3535+*+
0.000000
我想要达到的结果
程序可以正常运行