逆波兰表达式求值c++
时间: 2023-09-09 22:12:26 浏览: 167
您好!求解逆波兰表达式的C代码如下所示:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_LEN 100
typedef struct {
double *stack;
int top;
} Stack;
void init(Stack *s) {
s->stack = (double *)malloc(MAX_LEN * sizeof(double));
s->top = -1;
}
int isEmpty(Stack *s) {
return s->top == -1;
}
void push(Stack *s, double num) {
s->top++;
s->stack[s->top] = num;
}
double pop(Stack *s) {
if (isEmpty(s)) {
printf("Error: stack is empty!\n");
exit(1);
}
double num = s->stack[s->top];
s->top--;
return num;
}
double evaluateRPN(char *expression) {
Stack *s = (Stack *)malloc(sizeof(Stack));
init(s);
char *token = strtok(expression, " ");
while (token != NULL) {
if (isdigit(token[0]) || (token[0] == '-' && isdigit(token[1]))) {
double num = atof(token);
push(s, num);
} else if (strlen(token) == 1 && !isdigit(token[0])) {
double num2 = pop(s);
double num1 = pop(s);
double result;
switch (token[0]) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
printf("Error: invalid operator '%c'\n", token[0]);
exit(1);
}
push(s, result);
} else {
printf("Error: invalid token '%s'\n", token);
exit(1);
}
token = strtok(NULL, " ");
}
double result = pop(s);
free(s->stack);
free(s);
return result;
}
int main() {
char expression[MAX_LEN];
printf("Enter the reverse Polish notation expression: ");
fgets(expression, MAX_LEN, stdin);
// Remove the trailing newline character
expression[strlen(expression) - 1] = '\0';
double result = evaluateRPN(expression);
printf("Result: %.2f\n", result);
return 0;
}
```
这段代码使用了栈来求解逆波兰表达式,首先初始化一个栈,然后按照逆波兰表达式的规则逐个处理每个操作数和运算符。如果遇到操作数,则将其入栈;如果遇到运算符,则从栈中取出相应个数的操作数进行运算,并将结果入栈。最后栈中剩余的元素即为计算结果。
请注意,代码中使用空格作为分隔符来切分逆波兰表达式中的操作数和运算符,例如输入"2 3 +"表示2 + 3。计算结果会保留两位小数进行输出。
希望能帮到您!如果有任何疑问,请随时提出。
阅读全文