输入一个中缀算术表达式,求解表达式的值。运算符包括+、-、*、/、(、)、=,使用c++编写代码
时间: 2023-10-17 19:05:32 浏览: 412
我可以为您提供一个简单的中缀表达式求解程序,以下是使用C语言编写的代码:
```
#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 50
// 符号栈结构体
struct stack {
int items[STACK_SIZE];
int top;
};
// 初始化符号栈
void init_stack(struct stack *s) {
s->top = -1;
}
// 判断符号栈是否为空
int is_empty(struct stack *s) {
return s->top == -1;
}
// 判断符号栈是否已满
int is_full(struct stack *s) {
return s->top == STACK_SIZE - 1;
}
// 入栈操作
void push(struct stack *s, int item) {
if (is_full(s)) {
printf("\nStack is full!");
exit(1);
}
s->items[++s->top] = item;
}
// 出栈操作
int pop(struct stack *s) {
if (is_empty(s)) {
printf("\nInvalid expression!");
exit(1);
}
return s->items[s->top--];
}
// 获取栈顶元素
int peek(struct stack *s) {
if (is_empty(s)) {
printf("\nInvalid expression!");
exit(1);
}
return s->items[s->top];
}
// 判断是否为操作符
int is_operator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == ')');
}
// 判断操作符的优先级
int precedence(char c) {
if (c == '(' || c == ')') {
return 0;
}
if (c == '+' || c == '-') {
return 1;
}
if (c == '*' || c == '/') {
return 2;
}
return 0;
}
// 运算操作
int operate(int op1, int op2, char operator) {
switch (operator) {
case '+':
return op1 + op2;
case '-':
return op1 - op2;
case '*':
return op1 * op2;
case '/':
return op1 / op2;
}
return 0;
}
// 解析中缀表达式
int evaluate(char *expression) {
struct stack operand_stack, operator_stack;
int i, n, operand1, operand2;
char token, operator;
init_stack(&operand_stack);
init_stack(&operator_stack);
n = strlen(expression);
for (i = 0; i < n; i++) {
token = expression[i];
// 如果是数字,压入操作数栈
if (isdigit(token)) {
push(&operand_stack, token - '0');
}
// 如果是左括号,压入操作符栈
else if (token == '(') {
push(&operator_stack, token);
}
// 如果是右括号,将操作符栈中左括号之间的操作符依次弹出,并进行运算,最后将左括号弹出
else if (token == ')') {
while (peek(&operator_stack) != '(') {
operand2 = pop(&operand_stack);
operand1 = pop(&operand_stack);
operator = pop(&operator_stack);
push(&operand_stack, operate(operand1, operand2, operator));
}
pop(&operator_stack);
}
// 如果是操作符,需要进行进一步判断
else if (is_operator(token)) {
// 如果当前操作符优先级小于等于操作符栈顶的操作符,将操作符栈顶的操作符依次弹出,并进行运算
while (!is_empty(&operator_stack) && precedence(token) <= precedence(peek(&operator_stack))) {
operand2 = pop(&operand_stack);
operand1 = pop(&operand_stack);
operator = pop(&operator_stack);
push(&operand_stack, operate(operand1, operand2, operator));
}
// 将当前操作符压入操作符栈
push(&operator_stack, token);
}
}
// 处理剩余的操作符
while (!is_empty(&operator_stack)) {
operand2 = pop(&operand_stack);
operand1 = pop(&operand_stack);
operator = pop(&operator_stack);
push(&operand_stack, operate(operand1, operand2, operator));
}
// 返回最终结果
return pop(&operand_stack);
}
int main() {
char expression[50];
int result;
printf("Please input an infix arithmetic expression:\n");
scanf("%s", expression);
result = evaluate(expression);
printf("\nResult = %d", result);
return 0;
}
```
使用该程序求解中缀表达式的值时,需要注意输入表达式时需用括号括起来,例如:(1+2)*3。
阅读全文