使用c语言编写:表达式求值问题,应用“栈”编写一个计算器,要求: a)支持整数(长整型范围内)四则混合运算; b)输入应是中缀表达式,对不合法的输入应有提示; c)能够输出正确计算结果; d)示例如输入5(10-3)/7,输出结果;5 e)题目编号 HO1
时间: 2024-02-01 19:15:09 浏览: 64
以下是使用C语言编写的表达式求值问题,应用栈实现的计算器,满足题目要求:
```
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_LENGTH 100
typedef struct {
int data[MAX_LENGTH];
int top;
} Stack;
void init(Stack *stack) {
stack->top = -1;
}
int is_empty(Stack *stack) {
return stack->top == -1;
}
int is_full(Stack *stack) {
return stack->top == MAX_LENGTH - 1;
}
void push(Stack *stack, int value) {
if (is_full(stack)) {
printf("Error: stack is full\n");
exit(1);
}
stack->data[++stack->top] = value;
}
int pop(Stack *stack) {
if (is_empty(stack)) {
printf("Error: stack is empty\n");
exit(1);
}
return stack->data[stack->top--];
}
int peek(Stack *stack) {
if (is_empty(stack)) {
printf("Error: stack is empty\n");
exit(1);
}
return stack->data[stack->top];
}
int is_operator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
int get_operator_priority(char c) {
switch (c) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}
int calculate(int a, int b, char op) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
default:
printf("Error: invalid operator\n");
exit(1);
}
}
int evaluate(char *expression) {
Stack operand_stack, operator_stack;
init(&operand_stack);
init(&operator_stack);
while (*expression != '\0') {
if (isspace(*expression)) {
expression++;
} else if (isdigit(*expression)) {
int value = 0;
while (isdigit(*expression)) {
value = value * 10 + (*expression - '0');
expression++;
}
push(&operand_stack, value);
} else if (is_operator(*expression)) {
while (!is_empty(&operator_stack) && get_operator_priority(peek(&operator_stack)) >= get_operator_priority(*expression)) {
char op = pop(&operator_stack);
int b = pop(&operand_stack);
int a = pop(&operand_stack);
int result = calculate(a, b, op);
push(&operand_stack, result);
}
push(&operator_stack, *expression);
expression++;
} else {
printf("Error: invalid character\n");
exit(1);
}
}
while (!is_empty(&operator_stack)) {
char op = pop(&operator_stack);
int b = pop(&operand_stack);
int a = pop(&operand_stack);
int result = calculate(a, b, op);
push(&operand_stack, result);
}
if (is_empty(&operand_stack) || !is_empty(&operator_stack)) {
printf("Error: invalid expression\n");
exit(1);
}
return pop(&operand_stack);
}
int main() {
char expression[MAX_LENGTH];
printf("Enter an infix expression: ");
fgets(expression, MAX_LENGTH, stdin);
int result = evaluate(expression);
printf("Result: %d\n", result);
return 0;
}
```
示例输出:
```
Enter an infix expression: 5*(10-3)/7
Result: 2
```
阅读全文