中缀表达式求值c语言
时间: 2023-06-21 17:24:31 浏览: 175
中缀表达式求值可以通过将中缀表达式转换为后缀表达式,然后再对后缀表达式进行求值来实现。以下是一个简单的中缀表达式求值的示例程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define STACK_SIZE 100
typedef struct {
double data[STACK_SIZE];
int top;
} Stack;
void initStack(Stack* s) {
s->top = -1;
}
int isStackEmpty(Stack* s) {
return s->top == -1;
}
int isStackFull(Stack* s) {
return s->top == STACK_SIZE - 1;
}
void push(Stack* s, double data) {
if (isStackFull(s)) {
fprintf(stderr, "Stack overflow.\n");
exit(EXIT_FAILURE);
}
s->data[++s->top] = data;
}
double pop(Stack* s) {
if (isStackEmpty(s)) {
fprintf(stderr, "Stack underflow.\n");
exit(EXIT_FAILURE);
}
return s->data[s->top--];
}
int priority(char op) {
switch (op) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}
double evaluate(double op1, char operator, double op2) {
switch (operator) {
case '+':
return op1 + op2;
case '-':
return op1 - op2;
case '*':
return op1 * op2;
case '/':
return op1 / op2;
default:
fprintf(stderr, "Invalid operator: %c\n", operator);
exit(EXIT_FAILURE);
}
}
double evaluateInfixExpression(char* infix) {
Stack operatorStack;
double operandStack[STACK_SIZE];
int operandCount = 0;
char* token = strtok(infix, " ");
while (token != NULL) {
if (isdigit(token[0])) {
operandStack[operandCount++] = atof(token);
} else {
while (!isStackEmpty(&operatorStack) && priority(token[0]) <= priority(operatorStack.data[operatorStack.top])) {
double op2 = operandStack[--operandCount];
double op1 = operandStack[--operandCount];
char operator = pop(&operatorStack);
operandStack[operandCount++] = evaluate(op1, operator, op2);
}
push(&operatorStack, token[0]);
}
token = strtok(NULL, " ");
}
while (!isStackEmpty(&operatorStack)) {
double op2 = operandStack[--operandCount];
double op1 = operandStack[--operandCount];
char operator = pop(&operatorStack);
operandStack[operandCount++] = evaluate(op1, operator, op2);
}
return operandStack[0];
}
int main() {
char infix[STACK_SIZE];
printf("Enter an infix expression: ");
fgets(infix, sizeof(infix), stdin);
printf("Result: %f\n", evaluateInfixExpression(infix));
return 0;
}
```
该程序使用两个栈,一个用于存储操作符,另一个用于存储操作数。它首先将中缀表达式字符串分解成单词,然后扫描每个单词,如果它是一个操作数,则将其推入操作数栈,否则将其与操作符栈的栈顶元素进行比较。如果其优先级高于操作符栈的栈顶元素,则将其推入操作符栈,否则将操作符栈的栈顶元素弹出,与两个操作数栈的栈顶元素进行操作并将结果推入操作数栈。最后,当操作符栈为空时,操作数栈的栈顶元素即为表达式的值。
阅读全文
相关推荐
















