表达式求值,c语言代码
时间: 2023-09-04 17:15:38 浏览: 81
以下是一个简单的表达式求值程序的C语言代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_STACK_SIZE 50
typedef struct {
int top;
int items[MAX_STACK_SIZE];
} Stack;
void push(Stack *s, int val) {
if (s->top >= MAX_STACK_SIZE) {
printf("Stack overflow\n");
exit(1);
}
s->items[++(s->top)] = val;
}
int pop(Stack *s) {
if (s->top <= -1) {
printf("Stack underflow\n");
exit(1);
}
return s->items[(s->top)--];
}
int evaluate(char *expr) {
Stack s;
s.top = -1;
int i, op1, op2, result;
char ch;
for (i = 0; expr[i] != '\0'; i++) {
ch = expr[i];
if (isdigit(ch)) {
push(&s, ch - '0');
} else {
op2 = pop(&s);
op1 = pop(&s);
switch (ch) {
case '+':
result = op1 + op2;
break;
case '-':
result = op1 - op2;
break;
case '*':
result = op1 * op2;
break;
case '/':
result = op1 / op2;
break;
default:
printf("Invalid operator\n");
exit(1);
}
push(&s, result);
}
}
result = pop(&s);
return result;
}
int main() {
char expr[50];
printf("Enter an expression: ");
scanf("%s", expr);
printf("Result: %d\n", evaluate(expr));
return 0;
}
```
该程序使用一个栈来存储中间结果,并在遇到运算符时弹出栈中的两个操作数进行计算,并将结果压入栈中。程序假定输入的表达式符合规范,即不包含括号和空格,并且所有操作数都是一位数字。
阅读全文
相关推荐
















