输人一个中级算术表达式,求解表达式的值。运算符包括 “+” “_”wxo wp” “C wy”“=参加运算的数为 double 类型且为正数。(要求:直接使用中缀算术表达式进行计算,不能转换为后缀或前缀表达式再进行计算,只考虑二元运算即可。)用c语言实现
时间: 2023-09-09 17:14:30 浏览: 182
好的,您可以将中级算术表达式作为字符串输入,然后使用栈来解析和计算表达式。下面是一个简单的 C 代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MAX_SIZE 100
typedef struct {
double data[MAX_SIZE];
int top;
} Stack;
void push(Stack *stack, double num) {
if (stack->top == MAX_SIZE - 1) {
printf("Stack overflow\n");
exit(1);
}
stack->data[++stack->top] = num;
}
double pop(Stack *stack) {
if (stack->top == -1) {
printf("Stack underflow\n");
exit(1);
}
return stack->data[stack->top--];
}
int is_operator(char ch) {
return (ch == '+' || ch == '-' || ch == '*' || ch == '/');
}
double calculate(double num1, double num2, char op) {
double result;
switch(op) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/': result = num1 / num2; break;
}
return result;
}
double evaluate(char *expression) {
Stack num_stack;
num_stack.top = -1;
Stack op_stack;
op_stack.top = -1;
int i = 0;
while (expression[i] != '\0') {
if (expression[i] >= '0' && expression[i] <= '9') {
double num = 0;
while (expression[i] >= '0' && expression[i] <= '9') {
num = num * 10 + (expression[i] - '0');
i++;
}
push(&num_stack, num);
} else if (is_operator(expression[i])) {
while (op_stack.top != -1 && op_stack.data[op_stack.top] != '(' && (expression[i] == '*' || expression[i] == '/') && (op_stack.data[op_stack.top] == '+' || op_stack.data[op_stack.top] == '-')) {
double num2 = pop(&num_stack);
double num1 = pop(&num_stack);
char op = pop(&op_stack);
double result = calculate(num1, num2, op);
push(&num_stack, result);
}
push(&op_stack, expression[i]);
i++;
} else if (expression[i] == '(') {
push(&op_stack, expression[i]);
i++;
} else if (expression[i] == ')') {
while (op_stack.data[op_stack.top] != '(') {
double num2 = pop(&num_stack);
double num1 = pop(&num_stack);
char op = pop(&op_stack);
double result = calculate(num1, num2, op);
push(&num_stack, result);
}
pop(&op_stack);
i++;
} else {
i++;
}
}
while (op_stack.top != -1) {
double num2 = pop(&num_stack);
double num1 = pop(&num_stack);
char op = pop(&op_stack);
double result = calculate(num1, num2, op);
push(&num_stack, result);
}
return pop(&num_stack);
}
int main() {
char expression[MAX_SIZE];
printf("Enter an infix arithmetic expression: ");
fgets(expression, MAX_SIZE, stdin);
expression[strlen(expression)-1] = '\0'; // remove newline character
double result = evaluate(expression);
printf("Result: %lf\n", result);
return 0;
}
```
对于输入的中级算术表达式,程序会从左到右扫描每个字符。如果是数字,则将其压入数字栈;如果是运算符,则将其与操作符栈顶元素进行比较,如果当前的运算符优先级更低,则取出两个数字栈顶元素和一个操作符栈顶元素进行计算,并将结果压入数字栈。如果当前的运算符优先级更高,则将其压入操作符栈。如果是左括号,则将其压入操作符栈;如果是右括号,则取出数字栈顶的两个元素和操作符栈顶的一个元素进行计算,并将结果压入数字栈,直到遇到左括号。
最后,当操作符栈为空时,数字栈中的唯一元素就是表达式的计算结果。
阅读全文