星际公民在哪里可以玩:帮我看看我逆波兰表达的C程序

来源:百度文库 编辑:神马品牌网 时间:2024/04/26 23:49:39
主要帮我把式子给计算出结果

#include <stdlib.h>
#include <stdio.h>
const int MS=100;
typedef int SElemType;
typedef struct SqStack
{ char *base;
char *top;
char stacksize;
}SqStack;
//程序
void InitStack (SqStack &S)
{
S.base=(char *) malloc (MS *sizeof(char));
if (!S.base)
exit (0); //为栈S分配存储空间失败
S.top=S.base;
S.stacksize=MS;
}
int Push(SqStack &S,char ch)
{
if (S.top-S.base>S.stacksize) //Stack==full?
{ S.base=(char *)realloc(S.base,(S.stacksize+MS *sizeof(char)));
if (!S.base)
{ printf("Failure to reallocate the Memory units!:\n");
exit(0);
}
S.top=S.base+S.stacksize; S.stacksize+=MS;
}
*S.top++=ch; return(1);
}
int Pop(SqStack &S,char &ch)
{
if (S.top==S.base)
{
printf("下溢!");
return (0);
}
ch=*--S.top;
return (1);
}
void Translation()
{//
int i,j;
char str[100],exp[100],ch;
SqStack S;
InitStack(S);
i=1;
printf(" 请输入算术表达式字符串,求其逆波兰表达式,以#为结束标志,如a-b*c/(3+6)#:\n");
do
{
scanf("%c",&str[i]);
i++;
}while(str[i-1]!='#');
str[0]='('; //
str[i-1]=')';
str[i]='#';
i=0;
j=0;
while(str[i]!='#')
{ if((str[i]>='0' &&str[i]<='9')||(str[i]>='a' &&str[i]<='z'))
{
exp[j]=str[i];
j++;
} //end of if
else if(str[i]=='(')
Push(S,str[i]);
else if(str[i]==')')
{ while(*(S.top-1)!='(')
{ Pop(S,ch); exp[j]=ch; j++; }
S.top--;
} //end of elseif
else if(str[i]=='+'||str[i]=='-') { while((S.top!=S.base)&&(*(S.top-1)!='('))
{ Pop(S,ch); exp[j]=ch; j++; }
Push(S,str[i]);
} //end of else if
else if (str[i]=='*'||str[i]=='/')
{
while((*(S.top-1)=='*')||(*(S.top-1)=='/'))
{ Pop(S,ch); exp[j]=ch; j++; }
Push(S,str[i]);
} //end of else if
i++;
} //end of while
exp[j]='#';
printf("\n\n输入的算术表达式");
i=1;
while(str[i+1]!='#')
{ printf("%c",str[i]);
i++;
} //end of while
printf(" 逆波兰表达式为:\n");
i=0;
while(exp[i]!='#')
{ printf("%c",exp[i]); i++; }
}
void getch(char *exp)
{
SqStack S;
InitStack(S);
int x;
int i=0;
while(exp[i])
{
switch(str[i])
{
case '+':
x=Pop(&S)+Pop(&S);
i++;break;
case '-':
x=Pop(&S);
x=Pop-x;
i++;break;
case '*':
x=Pop(&S);
x=Pop(&S)*s;
i++;break;
case '/':
x=Pop(&S);
if(x!=0)
x=Pop(&S)/x;
else{
printf("除数为0!\n");
exit(1);
}
i++;break;
default:
x=0;
while((str[i]>='0' &&str[i]<='9')||(str[i]>='a' &&str[i]<='z'))
{
x=x*10+exp[i];
i++;
}
}
}
Push(&S,x);
}
printf("%d\n",x);
}

void main()
{
Translation();
printf("\n");
printf("…OK…!");
getch();

}

声明:我的编译环境是redhat linux9
1.如果这是个C程序的话,那么const 定义常量就是非法的。即便是在win32环境中,也不建议使用这种定义。
2.函数void getch(); 声明中有形式参数,而调用时没有形式参数,这是不允许的。
3.int Pop(SqStack &S,char &ch) 中存在两个参数,但是你调用时为什么只有一个参数。
4.x=Pop(&S)*s; 替换为 x=Pop(&S)*x;
5.在本程序中一个很普遍的问题,就是你把局部变量在当作全局变量来使用,这是无法实现的。
总体上来说你的程序有了太多的错误,加上没有注释,有没有适当的程序段分割,其可读性实在是太差,基本上属于无法了解你的核心算法,建议你重新写一次,添加必要的注释,适当的切分程序段落。这个样子别人是没办法帮你解决的。

http://www.ivdown.com/welcome.aspx?sid=31104