C语言:算数表达式求值,输入9+3*6,输出27
时间: 2024-02-28 18:56:47 浏览: 97
以下是一个基本的C语言算术表达式求值程序,可以实现你想要的功能:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_EXPR_LEN 100
typedef struct {
int top;
int data[MAX_EXPR_LEN];
} Stack;
void init(Stack *s) {
s->top = -1;
}
void push(Stack *s, int val) {
s->data[++s->top] = val;
}
int pop(Stack *s) {
return s->data[s->top--];
}
int peek(Stack *s) {
return s->data[s->top];
}
int is_empty(Stack *s) {
return s->top == -1;
}
int evaluate(char *expr) {
Stack operands;
Stack operators;
int i, op1, op2, result;
init(&operands);
init(&operators);
for (i = 0; expr[i] != '\0'; i++) {
if (isdigit(expr[i])) {
push(&operands, expr[i] - '0');
} else if (expr[i] == '+' || expr[i] == '-' || expr[i] == '*' || expr[i] == '/') {
while (!is_empty(&operators) && peek(&operators) != '(' && ((expr[i] == '*' || expr[i] == '/') || (expr[i] == '+' || expr[i] == '-') && (peek(&operators) == '*' || peek(&operators) == '/'))) {
op2 = pop(&operands);
op1 = pop(&operands);
switch (pop(&operators)) {
case '+':
result = op1 + op2;
break;
case '-':
result = op1 - op2;
break;
case '*':
result = op1 * op2;
break;
case '/':
result = op1 / op2;
break;
}
push(&operands, result);
}
push(&operators, expr[i]);
} else if (expr[i] == '(') {
push(&operators, expr[i]);
} else if (expr[i] == ')') {
while (peek(&operators) != '(') {
op2 = pop(&operands);
op1 = pop(&operands);
switch (pop(&operators)) {
case '+':
result = op1 + op2;
break;
case '-':
result = op1 - op2;
break;
case '*':
result = op1 * op2;
break;
case '/':
result = op1 / op2;
break;
}
push(&operands, result);
}
pop(&operators);
}
}
while (!is_empty(&operators)) {
op2 = pop(&operands);
op1 = pop(&operands);
switch (pop(&operators)) {
case '+':
result = op1 + op2;
break;
case '-':
result = op1 - op2;
break;
case '*':
result = op1 * op2;
break;
case '/':
result = op1 / op2;
break;
}
push(&operands, result);
}
return pop(&operands);
}
int main() {
char expr[MAX_EXPR_LEN];
printf("Enter an arithmetic expression: ");
scanf("%s", expr);
printf("Result: %d\n", evaluate(expr));
return 0;
}
```
你可以输入9+3*6,程序会输出27。
阅读全文