表达式求值c语言代码
时间: 2023-10-20 19:08:49 浏览: 136
要在C语言中实现表达式的求值,可以使用栈来辅助计算。栈的元素类型可以是运算符和运算数,使用两个栈分别存储运算符和运算数。具体的代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int top;
char* data;
} StackChar;
typedef struct {
int top;
float* data;
} StackFloat;
void initStackChar(StackChar* stack, int size) {
stack->top = -1;
stack->data = (char*)malloc(sizeof(char) * size);
}
void initStackFloat(StackFloat* stack, int size) {
stack->top = -1;
stack->data = (float*)malloc(sizeof(float) * size);
}
void pushChar(StackChar* stack, char value) {
stack->top++;
stack->data[stack->top] = value;
}
void pushFloat(StackFloat* stack, float value) {
stack->top++;
stack->data[stack->top] = value;
}
char popChar(StackChar* stack) {
char value = stack->data[stack->top];
stack->top--;
return value;
}
float popFloat(StackFloat* stack) {
float value = stack->data[stack->top];
stack->top--;
return value;
}
char topChar(StackChar* stack) {
return stack->data[stack->top];
}
float topFloat(StackFloat* stack) {
return stack->data[stack->top];
}
int isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
int precedence(char op) {
if (op == '*' || op == '/') {
return 2;
} else if (op == '+' || op == '-') {
return 1;
} else {
return 0;
}
}
float calculate(float a, float b, char op) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
default:
return 0;
}
}
float evaluateExpression(char* expression) {
int size = 100;
StackChar operatorStack;
StackFloat operandStack;
initStackChar(&operatorStack, size);
initStackFloat(&operandStack, size);
int i = 0;
while (expression[i] ! '#') {
if (expression[i] == ' ') {
i++;
continue;
}
if (isOperator(expression[i])) {
while (operatorStack.top != -1 && precedence(topChar(&operatorStack)) >= precedence(expression[i])) {
char op = popChar(&operatorStack);
float b = popFloat(&operandStack);
float a = popFloat(&operandStack);
float result = calculate(a, b, op);
pushFloat(&operandStack, result);
}
pushChar(&operatorStack, expression[i]);
} else {
float number = 0;
while (expression[i] >= '0' && expression[i] <= '9') {
number = number * 10 + (expression[i] - '0');
i++;
}
pushFloat(&operandStack, number);
continue;
}
i++;
}
while (operatorStack.top != -1) {
char op = popChar(&operatorStack);
float b = popFloat(&operandStack);
float a = popFloat(&operandStack);
float result = calculate(a, b, op);
pushFloat(&operandStack, result);
}
float finalResult = popFloat(&operandStack);
free(operatorStack.data);
free(operandStack.data);
return finalResult;
}
int main() {
char expression[100];
printf("请输入以#作为结束符的表达式: ");
gets(expression);
float result = evaluateExpression(expression);
printf("表达式的结果为: %.2f\n", result);
return 0;
}
```
以上是一个简单的表达式求值的C语言代码。该代码使用两个栈分别存储运算符和运算数,在读取表达式时,根据运算符的优先级决定是否进行计算,并将结果压入运算数栈中。最终,栈中剩余的运算符需要依次计算,并得出最终的结果。
阅读全文