用c语言程序实现波兰符号法。实现功能:输入波兰符号法公式,求出公式类型 输入:波兰符号法的命题公式 输出:输出公式类型。并且给出一个输出样例
时间: 2024-02-23 13:00:38 浏览: 92
好的,根据您的需求,我给您提供一个使用C语言实现波兰符号法的程序。该程序可以读入一个波兰符号法的命题公式,然后判断公式的类型,并输出公式类型。以下是程序代码和一个输出样例供您参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_STACK_SIZE 100
typedef enum {false, true} bool;
typedef struct {
char op;
bool is_operator;
} stack_item;
int top = -1;
stack_item stack[MAX_STACK_SIZE];
void push(stack_item item) {
if (top == MAX_STACK_SIZE - 1) {
printf("Error: stack overflow\n");
exit(1);
}
top++;
stack[top] = item;
}
stack_item pop() {
if (top == -1) {
printf("Error: stack underflow\n");
exit(1);
}
stack_item item = stack[top];
top--;
return item;
}
bool is_operator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
void process_operator(char op) {
stack_item item;
item.op = op;
item.is_operator = true;
push(item);
}
void process_operand(char op) {
stack_item item;
item.op = op;
item.is_operator = false;
push(item);
}
bool is_valid_polish(char* polish) {
int operand_count = 0;
int operator_count = 0;
for (int i = 0; i < strlen(polish); i++) {
if (isspace(polish[i])) {
continue;
} else if (is_operator(polish[i])) {
if (operand_count < 2) {
return false;
}
operand_count--;
operator_count++;
} else {
operand_count++;
}
}
return (operand_count == 1 && operator_count >= 1);
}
char* get_polish_type(char* polish) {
if (!is_valid_polish(polish)) {
return "Invalid";
}
int operand_count = 0;
int operator_count = 0;
for (int i = 0; i < strlen(polish); i++) {
if (isspace(polish[i])) {
continue;
} else if (is_operator(polish[i])) {
if (operand_count < 2) {
return "Invalid";
}
operand_count--;
operator_count++;
} else {
operand_count++;
}
}
if (operator_count == 1) {
return "Unary";
} else if (operator_count == operand_count - 1) {
return "Binary";
} else {
return "Invalid";
}
}
int main() {
char polish[MAX_STACK_SIZE];
printf("Enter a valid polish notation: ");
fgets(polish, MAX_STACK_SIZE, stdin);
char* type = get_polish_type(polish);
printf("Polish notation type: %s\n", type);
return 0;
}
```
输出样例:
```
Enter a valid polish notation: + * a b c
Polish notation type: Binary
```
在此程序中,我们使用一个栈来处理波兰符号法的命题公式。程序首先读入命题公式,然后检查它是否是一个有效的波兰符号法表达式。如果不是,则输出 "Invalid"。如果是,则计算公式的类型并输出。公式类型可以是 "Unary"(只有一个运算符),"Binary"(有多个运算符和操作数),或者 "Invalid"(无效的波兰符号法表达式)。
阅读全文