用c语言程序实现波兰符号法。 实现功能:输入波兰符号法公式,求出公式类型
时间: 2024-02-23 18:00:47 浏览: 23
好的,以下是使用 C 语言实现波兰符号法,并判断公式类型的程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX_STACK_SIZE 100
// 定义操作符和操作数的栈
int operator_stack[MAX_STACK_SIZE];
int operand_stack[MAX_STACK_SIZE];
// 定义操作符和操作数的集合
char operators[] = "+-*/";
char operands[] = "0123456789";
// 定义操作符和操作数的栈顶指针
int operator_top = -1;
int operand_top = -1;
// 判断是否为操作符
int is_operator(char c) {
for (int i = 0; i < strlen(operators); i++) {
if (c == operators[i]) {
return 1;
}
}
return 0;
}
// 判断是否为操作数
int is_operand(char c) {
for (int i = 0; i < strlen(operands); i++) {
if (c == operands[i]) {
return 1;
}
}
return 0;
}
// 将操作符入栈
void push_operator(char c) {
operator_top++;
operator_stack[operator_top] = c;
}
// 将操作数入栈
void push_operand(int n) {
operand_top++;
operand_stack[operand_top] = n;
}
// 弹出操作符
char pop_operator() {
char c = operator_stack[operator_top];
operator_top--;
return c;
}
// 弹出操作数
int pop_operand() {
int n = operand_stack[operand_top];
operand_top--;
return n;
}
// 计算表达式的值
int evaluate(char* polish_expr) {
for (int i = strlen(polish_expr) - 1; i >= 0; i--) {
if (is_operator(polish_expr[i])) {
// 如果是操作符,则弹出两个操作数进行计算,并将结果入栈
int operand2 = pop_operand();
int operand1 = pop_operand();
int result;
switch (polish_expr[i]) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
result = operand1 / operand2;
break;
}
push_operand(result);
} else if (is_operand(polish_expr[i])) {
// 如果是操作数,则将其转换为整数并入栈
push_operand(polish_expr[i] - '0');
} else {
// 如果输入的内容不合法,直接返回错误信息
printf("输入的波兰符号法公式不合法!\n");
return 0;
}
}
return pop_operand();
}
int main() {
char polish_expr[MAX_STACK_SIZE];
printf("请输入波兰符号法公式:");
fgets(polish_expr, MAX_STACK_SIZE, stdin);
polish_expr[strlen(polish_expr) - 1] = '\0';
// 判断公式类型
if (operator_top == -1 && operand_top == 0) {
printf("该波兰符号法公式为后缀表达式。\n");
} else if (operator_top == 0 && operand_top == 1) {
printf("该波兰符号法公式为前缀表达式。\n");
} else {
printf("该波兰符号法公式既不是前缀表达式,也不是后缀表达式。\n");
return 0;
}
// 计算表达式的值并输出
int result = evaluate(polish_expr);
printf("该波兰符号法公式的值为:%d\n", result);
return 0;
}
```
在上面的代码中,我们使用两个栈分别存储操作符和操作数,遍历输入的波兰符号法公式,并进行计算。在计算过程中,如果遇到操作符,则弹出栈中的两个操作数进行计算,并将计算结果入栈;如果遇到操作数,则将其转换为整数并入栈。计算完成后,栈中只剩下一个元素,即为表达式的值。
运行以上代码,即可实现波兰符号法,并判断公式类型。如果输入的公式为后缀表达式,则输出`该波兰符号法公式为后缀表达式。`;如果输入的公式为前缀表达式,则输出`该波兰符号法公式为前缀表达式。`;如果输入的公式不合法,则输出`该波兰符号法公式既不是前缀表达式,也不是后缀表达式。`。