算数表达式求值c语言代码
时间: 2024-03-24 11:34:13 浏览: 104
当涉及算数表达式求值的C语言代码时,可以使用栈来实现。以下是一个简单的算数表达式求值的C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义栈结构
typedef struct {
int top;
int capacity;
int* array;
} Stack;
// 创建栈
Stack* createStack(int capacity) {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->top = -1;
stack->capacity = capacity;
stack->array = (int*)malloc(stack->capacity * sizeof(int));
return stack;
}
// 判断栈是否为空
int isEmpty(Stack* stack) {
return stack->top == -1;
}
// 判断栈是否已满
int isFull(Stack* stack) {
return stack->top == stack->capacity - 1;
}
// 入栈
void push(Stack* stack, int item) {
if (isFull(stack)) {
printf("栈已满,无法入栈\n");
return;
}
stack->array[++stack->top] = item;
}
// 出栈
int pop(Stack* stack) {
if (isEmpty(stack)) {
printf("栈为空,无法出栈\n");
return -1;
}
return stack->array[stack->top--];
}
// 获取栈顶元素
int peek(Stack* stack) {
if (isEmpty(stack)) {
printf("栈为空\n");
return -1;
}
return stack->array[stack->top];
}
// 判断字符是否为操作符
int isOperator(char ch) {
return (ch == '+' || ch == '-' || ch == '*' || ch == '/');
}
// 执行算术运算
int performOperation(char operator, int operand1, int operand2) {
switch (operator) {
case '+':
return operand1 + operand2;
case '-':
return operand1 - operand2;
case '*':
return operand1 * operand2;
case '/':
return operand1 / operand2;
default:
printf("无效的操作符\n");
return -1;
}
}
// 算数表达式求值函数
int evaluateExpression(char* expression) {
Stack* stack = createStack(strlen(expression));
int i;
for (i = 0; i < strlen(expression); i++) {
if (expression[i] == ' ' || expression[i] == ',') {
continue;
} else if (isOperator(expression[i])) {
int operand2 = pop(stack);
int operand1 = pop(stack);
int result = performOperation(expression[i], operand1, operand2);
push(stack, result);
} else if (isdigit(expression[i])) {
int operand = 0;
while (i < strlen(expression) && isdigit(expression[i])) {
operand = (operand * 10) + (expression[i] - '0');
i++;
}
i--;
push(stack, operand);
}
}
return pop(stack);
}
int main() {
char expression[100];
printf("请输入算数表达式:");
fgets(expression, sizeof(expression), stdin);
int result = evaluateExpression(expression);
printf("表达式的结果为:%d\n", result);
return 0;
}
```
这段代码使用了栈来实现算数表达式的求值。它首先创建了一个栈结构,然后通过遍历表达式的每个字符,判断字符类型并执行相应的操作。具体来说,如果遇到操作符,则从栈中弹出两个操作数,并执行相应的运算,将结果压入栈中;如果遇到数字,则将连续的数字字符转换为整数,并将其压入栈中。最后,从栈中弹出的结果即为表达式的求值结果。
阅读全文