编写包含栈的程序,完成手机计算机器中的简单表达式求值,完成+、-、*、/、% 五种混合运算和以下要求的C语言代码 1.无括号、整数 2.有括号、整数 3.有括号、多位整数
时间: 2024-01-01 15:06:09 浏览: 110
以下是实现上述要求的C语言代码:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int top;
int data[MAX_SIZE];
} Stack;
void init(Stack *s) {
s->top = -1;
}
int is_empty(Stack *s) {
return s->top == -1;
}
int is_full(Stack *s) {
return s->top == MAX_SIZE - 1;
}
void push(Stack *s, int x) {
if (is_full(s)) {
printf("Stack overflow\n");
exit(1);
}
s->data[++s->top] = x;
}
int pop(Stack *s) {
if (is_empty(s)) {
printf("Stack underflow\n");
exit(1);
}
return s->data[s->top--];
}
int peek(Stack *s) {
if (is_empty(s)) {
printf("Stack underflow\n");
exit(1);
}
return s->data[s->top];
}
int is_operator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '%';
}
int precedence(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/' || op == '%') {
return 2;
} else {
return 0;
}
}
int evaluate_expression(char *exp) {
Stack operand_stack;
Stack operator_stack;
init(&operand_stack);
init(&operator_stack);
int i = 0;
while (exp[i] != '\0') {
if (exp[i] == '(') {
push(&operator_stack, exp[i]);
} else if (exp[i] == ')') {
while (!is_empty(&operator_stack) && peek(&operator_stack) != '(') {
char op = pop(&operator_stack);
int b = pop(&operand_stack);
int a = pop(&operand_stack);
int result;
switch (op) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
case '%':
result = a % b;
break;
}
push(&operand_stack, result);
}
pop(&operator_stack);
} else if (is_operator(exp[i])) {
while (!is_empty(&operator_stack) && peek(&operator_stack) != '(' && precedence(exp[i]) <= precedence(peek(&operator_stack))) {
char op = pop(&operator_stack);
int b = pop(&operand_stack);
int a = pop(&operand_stack);
int result;
switch (op) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
case '%':
result = a % b;
break;
}
push(&operand_stack, result);
}
push(&operator_stack, exp[i]);
} else {
int num = 0;
while (exp[i] >= '0' && exp[i] <= '9') {
num = num * 10 + exp[i] - '0';
i++;
}
push(&operand_stack, num);
continue;
}
i++;
}
while (!is_empty(&operator_stack)) {
char op = pop(&operator_stack);
int b = pop(&operand_stack);
int a = pop(&operand_stack);
int result;
switch (op) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
case '%':
result = a % b;
break;
}
push(&operand_stack, result);
}
return pop(&operand_stack);
}
int main() {
char exp[MAX_SIZE];
printf("Enter expression: ");
scanf("%s", exp);
int result = evaluate_expression(exp);
printf("Result: %d\n", result);
return 0;
}
```
注意:该程序只支持整数运算,不支持浮点数运算。如果需要支持浮点数运算,请修改相关代码。
阅读全文