首先,可以使用 scanf 函数从键盘输入一个字符串,然后使用栈来处理这个字符串并计算表达式的结果。
代码示例如下:
``` #include <stdio.h> #include <stdlib.h> #include <ctype.h>
#define MAX_STACK_SIZE 100
// 定义栈结构体 typedef struct { double data[MAX_STACK_SIZE]; int top; } Stack;
// 初始化栈 void init_stack(Stack* stack) { stack->top = -1; }
// 判断栈是否为空 int is_empty(Stack* stack) { return stack->top == -1; }
// 判断栈是否已满 int is_full(Stack* stack) { return stack->top == MAX_STACK_SIZE - 1; }
// 入栈 void push(Stack* stack, double value) { if (is_full(stack)) { printf("Error: stack is full.\n"); exit(1); } stack->data[++stack->top] = value; }
// 出栈 double pop(Stack* stack) { if (is_empty(stack)) { printf("Error: stack is empty.\n"); exit(1); } return stack->data[stack->top--]; }
// 获取栈顶元素 double peek(Stack* stack) { if (is_empty(stack)) { printf("Error: stack is empty.\n"); exit(1); } return stack->data[stack->top]; }
int main(int argc, char* argv[]) { char expression[MAX_STACK_SIZE]; // 定义一个字符数组来存储表达式 printf("Please enter an arithmetic expression: "); scanf("%s", expression); // 从键盘输入表达式
Stack operand_stack; // 定义一个操作数栈 init_stack(&operand_stack); // 初始化操作数栈
Stack operator_stack; // 定义一个操作符栈 init_stack(&operator_stack); // 初始化操作符栈
// 遍历表达式中的每个字