用C++编写一个中缀转后缀的代码,满足加减乘除四则运算和取余运算
时间: 2023-03-31 18:03:37 浏览: 117
C++实现中缀表达式转后缀表达式
5星 · 资源好评率100%
好的,我可以回答这个问题。以下是一个用 C 语言编写的中缀转后缀的代码,可以实现加减乘除四则运算和取余运算:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_STACK_SIZE 100
typedef enum {
lparen, rparen, plus, minus, times, divide, mod, eos, operand
} precedence;
int isp[] = {, 19, 12, 12, 13, 13, 13, };
int icp[] = {20, 19, 12, 12, 13, 13, 13, };
precedence getToken(char *symbol, int *n) {
*symbol = getchar();
switch (*symbol) {
case '(': return lparen;
case ')': return rparen;
case '+': return plus;
case '-': return minus;
case '*': return times;
case '/': return divide;
case '%': return mod;
case '\n': return eos;
default: return operand;
}
}
void postfix(void) {
char symbol;
precedence token;
int n = ;
int top = ;
int stack[MAX_STACK_SIZE];
stack[] = eos;
for (token = getToken(&symbol, &n); token != eos; token = getToken(&symbol, &n)) {
if (token == operand) {
printf("%c", symbol);
} else if (token == rparen) {
while (stack[top] != lparen) {
switch (stack[top--]) {
case plus: printf("+"); break;
case minus: printf("-"); break;
case times: printf("*"); break;
case divide: printf("/"); break;
case mod: printf("%%"); break;
}
}
} else {
while (isp[stack[top]] >= icp[token]) {
switch (stack[top--]) {
case plus: printf("+"); break;
case minus: printf("-"); break;
case times: printf("*"); break;
case divide: printf("/"); break;
case mod: printf("%%"); break;
}
}
stack[++top] = token;
}
}
while ((token = stack[top--]) != eos) {
switch (token) {
case plus: printf("+"); break;
case minus: printf("-"); break;
case times: printf("*"); break;
case divide: printf("/"); break;
case mod: printf("%%"); break;
}
}
printf("\n");
}
int main(void) {
postfix();
return ;
}
阅读全文