使用C语言1.表达式求值问题,应用“栈”编写一个计算器,要求: a)支持整数(长整型范围内)四则混合运算; b)输入应是中缀表达式,对不合法的输入应有提示; c)能够输出正确计算结果; d)示例如输入5(10-3)/7,输出结果5
时间: 2024-02-05 16:14:02 浏览: 71
以下是使用C语言实现的计算器,通过栈实现中缀表达式求值:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h> // 包含 isdigit() 函数
#define MAX_STACK_SIZE 100 // 栈的最大容量
typedef struct {
int top;
int data[MAX_STACK_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_STACK_SIZE - 1;
}
void push(Stack *s, int value) {
if (is_full(s)) {
printf("Stack is full.\n");
exit(1);
}
s->data[++s->top] = value;
}
int pop(Stack *s) {
if (is_empty(s)) {
printf("Stack is empty.\n");
exit(1);
}
return s->data[s->top--];
}
int peek(Stack *s) {
if (is_empty(s)) {
printf("Stack is empty.\n");
exit(1);
}
return s->data[s->top];
}
int is_operator(char ch) {
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
int priority(char op) {
if (op == '+' || op == '-')
return 1;
if (op == '*' || op == '/')
return 2;
return 0;
}
int evaluate(char *expr) {
Stack operand_stack;
Stack operator_stack;
init(&operand_stack);
init(&operator_stack);
int i = 0;
while (expr[i] != '\0') {
if (isdigit(expr[i])) {
int value = 0;
while (isdigit(expr[i])) {
value = value * 10 + expr[i] - '0';
i++;
}
push(&operand_stack, value);
} else if (is_operator(expr[i])) {
while (!is_empty(&operator_stack) && priority(peek(&operator_stack)) >= priority(expr[i])) {
int op = pop(&operator_stack);
int op1 = pop(&operand_stack);
int op2 = pop(&operand_stack);
int result;
switch (op) {
case '+':
result = op2 + op1;
break;
case '-':
result = op2 - op1;
break;
case '*':
result = op2 * op1;
break;
case '/':
result = op2 / op1;
break;
}
push(&operand_stack, result);
}
push(&operator_stack, expr[i]);
i++;
} else if (expr[i] == '(') {
push(&operator_stack, expr[i]);
i++;
} else if (expr[i] == ')') {
while (peek(&operator_stack) != '(') {
int op = pop(&operator_stack);
int op1 = pop(&operand_stack);
int op2 = pop(&operand_stack);
int result;
switch (op) {
case '+':
result = op2 + op1;
break;
case '-':
result = op2 - op1;
break;
case '*':
result = op2 * op1;
break;
case '/':
result = op2 / op1;
break;
}
push(&operand_stack, result);
}
pop(&operator_stack);
i++;
} else {
printf("Invalid input.\n");
exit(1);
}
}
while (!is_empty(&operator_stack)) {
int op = pop(&operator_stack);
int op1 = pop(&operand_stack);
int op2 = pop(&operand_stack);
int result;
switch (op) {
case '+':
result = op2 + op1;
break;
case '-':
result = op2 - op1;
break;
case '*':
result = op2 * op1;
break;
case '/':
result = op2 / op1;
break;
}
push(&operand_stack, result);
}
return peek(&operand_stack);
}
int main(void) {
char expr[MAX_STACK_SIZE];
printf("Enter an expression: ");
fgets(expr, MAX_STACK_SIZE, stdin);
int result = evaluate(expr);
printf("Result: %d\n", result);
return 0;
}
```
使用上述代码,你可以输入一个中缀表达式,然后程序会计算并输出结果。例如,输入 `5*(10-3)/7`,输出 `Result: 2`。
阅读全文