求值的程序怎么写

时间:2025-01-17 18:20:38 游戏攻略

求值程序的编写可以采用多种方法,包括使用栈结构、递归、正则表达式等。以下是一个使用C语言编写的简单表达式求值程序的示例:

```c

include

include

include

include

define MAX_EXP_LEN 1000

typedef struct {

int *array;

int size;

int top;

} Stack;

void initStack(Stack *s, int size) {

s->array = (int *)malloc(size * sizeof(int));

s->size = size;

s->top = -1;

}

int isEmpty(Stack *s) {

return s->top == -1;

}

int isFull(Stack *s) {

return s->top == s->size - 1;

}

void push(Stack *s, int data) {

if (isFull(s)) {

printf("Error: Stack is full.\n");

return;

}

s->top++;

s->array[s->top] = data;

}

int pop(Stack *s) {

if (isEmpty(s)) {

printf("Error: Stack is empty.\n");

return -1;

}

return s->array[s->top--];

}

double deal_exp(char *exp) {

Stack optr, opnd;

initStack(&optr, 10);

initStack(&opnd, 10);

int i = 0;

while (exp[i] != '\0') {

if (isdigit(exp[i])) {

int num = 0;

while (isdigit(exp[i])) {

num = num * 10 + (exp[i] - '0');

i++;

}

push(&opnd, num);

} else if (exp[i] == '(') {

push(&optr, '(');

} else if (exp[i] == ')') {

while (optr.top >= 0 && optr.array[optr.top] != '(') {

push(&opnd, pop(&optr));

}

pop(&optr); // pop '('

} else if (exp[i] == '+' || exp[i] == '-' || exp[i] == '*' || exp[i] == '/') {

while (!isEmpty(&optr) && precedence(exp[i]) <= precedence(optr.array[optr.top])) {

push(&opnd, pop(&optr));

}

push(&optr, exp[i]);

}

i++;

}

while (!isEmpty(&optr)) {

push(&opnd, pop(&optr));

}

double result = pop(&opnd);

free(optr.array);

free(opnd.array);

return result;

}

int precedence(char op) {

switch (op) {

case '+':

case '-':

return 1;

case '*':

case '/':

return 2;

default:

return -1;

}

}

int main() {

char exp[MAX_EXP_LEN];

printf("Enter an expression: ");

fgets(exp, MAX_EXP_LEN, stdin);

exp[strcspn(exp, "\n")] = 0; // remove newline character

double result = deal_exp(exp);

printf("Result: %f\n", result);

return 0;

}

```

代码说明:

栈结构:

定义了一个栈结构体 `Stack`,包含数组指针 `array`、栈大小 `size` 和栈顶指针 `top`。

栈操作:

实现了栈的初始化、判断栈是否为空或已满、入栈和出栈等操作。

表达式求值:

`deal_exp` 函数通过遍历表达式字符串,使用栈来处理运算符和操作数,最终计算出表达式的值。

优先级判断:

`precedence` 函数用于判断运算符的优先级。

主函数:

`main` 函数从键盘读取表达式,调用 `deal_