输入格式: 在一行中输入一个后缀式,运算数和运算符之间用空格分隔,运算数长度不超过6位,运算符仅有+ - * / 四种。 输出格式: 在一行中输出后缀式的值,保留一位小数。给出c语言代码实现后缀表达式求和
时间: 2023-06-02 14:06:50 浏览: 89
抱歉,我可以回答这个问题。以下是C语言中实现后缀表达式求和的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
// 定义堆栈结构
#define MAX_STACK_SIZE 100
typedef struct {
int top;
float data[MAX_STACK_SIZE];
} Stack;
// 初始化堆栈
void initStack(Stack *stack) {
stack->top = -1;
}
// 入栈
void push(Stack *stack, float value) {
if (stack->top >= MAX_STACK_SIZE - 1) {
printf("Error: Stack overflow!\n");
exit(1);
}
stack->data[++stack->top] = value;
}
// 出栈
float pop(Stack *stack) {
if (stack->top == -1) {
printf("Error: Stack underflow!\n");
exit(1);
}
return stack->data[stack->top--];
}
// 后缀表达式求值
float evaluatePostfix(char *postfix) {
Stack stack;
float a, b;
initStack(&stack);
char *token = strtok(postfix, " ");
while (token != NULL) {
if (isdigit(token[0])) {
push(&stack, atof(token));
} else {
b = pop(&stack);
a = pop(&stack);
switch (token[0]) {
case '+':
push(&stack, a + b);
break;
case '-':
push(&stack, a - b);
break;
case '*':
push(&stack, a * b);
break;
case '/':
push(&stack, a / b);
break;
}
}
token = strtok(NULL, " ");
}
return pop(&stack);
}
int main() {
char postfix[100];
fgets(postfix, 100, stdin);
postfix[strlen(postfix) - 1] = '\0'; // 去掉末尾的'\n'
printf("%.1f\n", evaluatePostfix(postfix));
return 0;
}
```
输入示例:`5 1 2 + 4 * + 3 -`
输出示例:`14.0`