#include<bits/stdc++.h> using namespace std; int yxj[128],top=0; char st[25],s[25]; int main() { yxj['+']=1; yxj['-']=1; yxj['*']=2; yxj['/']=2; yxj['(']=-1; while(~scanf("%s",s)){ int i=0; int j=0; int w; if(s<=9&&s>=0)cout<<s<<" ";i++;//是数字,将其输出 else if(top=0&&s!<=9&&s!>=0)st[j]==s;i++;j++;top++;//栈中没有值,就直接将运算符放入 else if(s=='(')st[j]==s;i++;j++;top++;w=i;//当前是左括号,直接放入 else if(s==')'){ s=" ";; top--; j--; while(s==')'){ cout>>s<<" "; w++; j--; top--; } }//当前是右括号,取出栈顶的运算符直到左括号为止,并且将左括号弹出 else if(yxj[s]==2)st[j]==s;j++;i++;top++;//当前运算符优先级较高,直接放入 else { w=i; while(yxj[s]==2){ cout>>s<<" "; w++; j--; top--; } } //当前运算符优先级小于等于栈顶运算符优先级,则不断弹出栈顶运算符直到当前运算符优先级较高 } while(top);//结束后将栈中运算符输出 }
时间: 2024-04-17 14:25:26 浏览: 18
这段代码是一个将中缀表达式转换为后缀表达式的实现。它使用了一个数组 `yxj` 来存储运算符的优先级,`top` 表示栈顶指针,`st` 数组用于存储运算符,`s` 数组用于存储输入的表达式。
代码的主要思路是遍历输入的表达式,根据当前字符的类型进行不同的操作。如果是数字,则直接输出;如果栈为空,则将运算符放入栈中;如果是左括号,则直接放入栈中;如果是右括号,则从栈中取出运算符直到遇到左括号,并将左括号弹出;如果当前运算符优先级较高,则直接放入栈中;如果当前运算符优先级小于等于栈顶运算符优先级,则不断弹出栈顶运算符直到当前运算符优先级较高。
最后,将栈中剩余的运算符输出即可得到后缀表达式。
需要注意的是,代码中存在一些错误。比如在判断数字时,应该使用 `s[i] >= '0' && s[i] <= '9'`,而不是 `s <= 9 && s >= 0`;在赋值运算符时,应该使用 `st[j] = s`,而不是 `st[j] == s`;在输出运算符时,应该使用 `cout << s << " "`,而不是 `cout >> s << " "`。
另外,代码中的 `while(top)` 应该改为 `while (top > 0)`。
修正后的代码如下所示:
```cpp
#include<bits/stdc++.h>
using namespace std;
int yxj[128],top=0;
char st[25],s[25];
int main()
{
yxj['+'] = 1;
yxj['-'] = 1;
yxj['*'] = 2;
yxj['/'] = 2;
yxj['('] = -1;
while(~scanf("%s",s)){
int i = 0;
int j = 0;
int w;
if(s[i] >= '0' && s[i] <= '9') {
cout << s << " ";
i++;
} else if(top == 0 && !(s[i] >= '0' && s[i] <= '9')) {
st[j] = s[i];
i++;
j++;
top++;
} else if(s[i] == '(') {
st[j] = s[i];
i++;
j++;
top++;
w = i;
} else if(s[i] == ')') {
s = " ";
top--;
j--;
while(s == ')') {
cout << s << " ";
w++;
j--;
top--;
}
} else if(yxj[s[i]] == 2) {
st[j] = s[i];
j++;
i++;
top++;
} else {
w = i;
while(yxj[s[i]] == 2) {
cout << s << " ";
w++;
j--;
top--;
}
}
}
while(top > 0) {
// 输出栈中剩余的运算符
}
}
```
请注意,这只是修正了代码中的一些错误,还需要根据实际需求来完善输出栈中剩余的运算符的部分。