这是我编写的将infix表达式转换为postfix表达式而不使用c语言结构的代码。但是有时它会产生意外的输出,有时会显示“分段错误”错误。此代码中的错误是什么?>
#include<stdio.h>
#define size 50
int top=-1;
char s[size];
void push(char ch){
s[++top] = ch;
}
char pop(){
char ch = s[top--];return ch;
}
int pr(char elem)
{
switch(elem)
{
case '#': return 0;
case '(': return 1;
case '+':
case '-': return 2;
case '*':
case '/': return 3;
case '^':
case '$': return 4;
}
}
int main(){
char in[50],post[50],ch,br;
int i=0,p=0;
printf("\n\nenter the Infix Expression : ");
scanf("%s",in);
push('#');
while(in[i++] != '\0'){
ch=in[i];
if((ch>=48 && ch<=57) || (ch>=65 && ch<=90) || (ch>=97 && ch<=122))
post[p++] = ch;
else if(ch == '(')
push(ch);
else if(ch == ')'){
while(s[top] != '(')
post[p++]=pop();
br = pop();
}
else if(ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^' || ch == '$'){
while(pr(s[top]) >= pr(ch))
post[p++] = pop();
push(ch); //if priority is less,only push will occur
}
//i++;
}
while( s[top] != '#')
post[p++]=pop();
post[p] = '\0';
printf("\ninfix : %s \n postfix : %s\n",in,post);
return 0;
}
答案 0 :(得分:0)
这是已调试的代码。while条件出现错误。我正在对其进行更新,然后将其存储在ch
#include<stdio.h>
#define size 50
int top=-1;
char s[size];
void push(char ch){
s[++top] = ch;
}
char pop(){
char ch = s[top--];return ch;
}
int pr(char br)
{
switch(br)
{
case '#': return 0;
case '(': return 1;
case '+':
case '-': return 2;
case '*':
case '/': return 3;
case '^':
case '$': return 4;
}
}
void main(){
char in[50],post[50],ch,br;
int i=0,p=0;
printf("\n\nenter the Infix Expression : ");
scanf("%s",in);
push('#');
while( (ch=in[i++]) != '\0'){
if((ch>=48 && ch<=57) || (ch>=65 && ch<=90) || (ch>=97 && ch<=122))
post[p++] = ch;
else if(ch == '(')
push(ch);
else if(ch == ')'){
while(s[top] != '(')
post[p++]=pop();
br = pop();
}
else if(ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^' || ch == '$'){
while( pr(s[top]) >= pr(ch) )
post[p++]=pop();
push(ch); //if priority is less,only push will occur
}
//i++;
}
while( s[top] != '#')
post[p++]=pop();
post[p] = '\0';
printf("\ninfix : %s \n postfix : %s\n",in,post);
}