gpt4 book ai didi

c - 我需要帮助在 C 中从中缀转换为后缀

转载 作者:太空宇宙 更新时间:2023-11-03 23:37:20 25 4
gpt4 key购买 nike

我正在练习以前做过的一些数据结构问题,但这次我不知道我的代码出了什么问题。我查看了很长时间,但没有发现错误。当我打印时,我只是得到第一个字符,看起来 e 没有被更新。但我写过 e++。

#include<stdio.h>
#include "ctype.h"
int stack[20];
int top = -1;

void push(int x)
{
stack[++top] = x;
}

int pop()
{
return stack[top--];
}
int priorityof(char x)
{
if(x=='(')
return 3;
else if(x=='+'|| x=='-')
return 1;
else if(x=='*'|| x=='/')
return 2;
}

int main()
{
char exp[20];
char *e;
e=exp;char x;
scanf("%c",exp);
while(*e!='\0')
{
if(isalnum(*e))
{
printf("%c", *e);
}
else if(*e=='(')
{
push(*e);
}
else if(*e==')')
{
while((x=pop())!='(')
printf("%c",x);
}
else {
while (priorityof(stack[top]) >= priorityof(*e)) {
printf("%c", pop());
push(*e);
}

}
e++;
}
while(top!=-1)
{
printf("%c",pop());
}
}

最佳答案

%c 用于单个字符,阅读您的问题似乎您提供了多个字符,因此它是一个字符串,请使用 %s


#include<stdio.h>
#include "ctype.h"
int stack[20]; int top = -1;
void push(int x) {
stack[++top] = x;
}
int pop() { return stack[top--]; }
int priorityof(char x) {
if(x=='(') return 3;
else if(x=='+'|| x=='-') return 1;
else if(x=='*'|| x=='/') return 2;
}
int main() {
char exp[20];
char *e;
e=exp;char x;
scanf("%s",exp);
while(*e!='\0') { if(isalnum(*e)) { printf("%c", *e); } else if(*e=='(') { push(*e); } else if(*e==')') { while((x=pop())!='(') printf("%c",x); } else { while (priorityof(stack[top]) >= priorityof(*e)) { printf("%c", pop()); push(*e); } } e++; } while(top!=-1) { printf("%c",pop()); } }

关于c - 我需要帮助在 C 中从中缀转换为后缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55783314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com