用c语言把算术式转变成后缀形式
时间: 2023-11-06 10:03:06 浏览: 43
算术式转换成后缀形式的过程可以通过使用栈来实现。下面是用C语言实现将算术式转换成后缀形式的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
// 初始化操作符优先级
int getPriority(char op) {
if (op == '+' || op == '-') {
return 1;
}
else if(op == '*' || op == '/' || op == '%') {
return 2;
}
else {
return 0;
}
}
// 将中缀表达式转换为后缀表达式
void infixToPostfix(char* infix, char* postfix) {
char stack[MAX_SIZE]; // 运算符栈
int top = -1; // 栈顶指针
int len = strlen(infix);
int index = 0; // 后缀表达式索引
for (int i = 0; i < len; i++) {
char ch = infix[i];
// 如果是数字,直接放入后缀表达式
if (ch >= '0' && ch <= '9') {
postfix[index++] = ch;
}
// 如果是运算符
else {
// 如果栈为空,或者当前运算符优先级大于栈顶运算符,则直接入栈
if (top == -1 || getPriority(ch) > getPriority(stack[top])) {
stack[++top] = ch;
}
else {
// 优先级小于等于栈顶运算符的,先将栈中运算符出栈,再将当前运算符入栈
while (top != -1 && getPriority(ch) <= getPriority(stack[top])) {
postfix[index++] = stack[top--];
}
stack[++top] = ch;
}
}
}
// 将栈中剩余的运算符出栈
while (top != -1) {
postfix[index++] = stack[top--];
}
postfix[index] = '\0'; // 后缀表达式结束标志
}
int main() {
char infix[MAX_SIZE];
char postfix[MAX_SIZE];
printf("请输入中缀表达式:");
scanf("%s", infix);
infixToPostfix(infix, postfix);
printf("后缀表达式:%s\n", postfix);
return 0;
}
```
这段代码实现了将中缀表达式转换为后缀表达式的功能。用户输入中缀表达式后,程序会将其转换为后缀形式并输出。示例输入:"3+4*2/(1-5)",输出:"342*15-/+"。