编写自定义函数: 1.关于运算符栈和操作数栈的初始化、进栈、出栈、取栈顶元素 2.根据运算符“+、−、*、/”返回相应操作数的结果 3.输入表达式并得到相应计算值 C语言编写
时间: 2024-10-27 17:03:24 浏览: 8
在C语言中,编写一个简单的四则运算计算器涉及到操作符栈和操作数栈的管理,我们可以创建两个栈结构体,一个用于存储操作数,另一个用于存储运算符。这里是一个基本的示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Stack {
int top;
int capacity;
double items[100];
} Stack;
Stack *create_stack(int size) {
Stack *stack = (Stack*)malloc(sizeof(Stack));
stack->top = -1;
stack->capacity = size;
return stack;
}
void push(Stack *stack, double item) {
if (stack->top >= stack->capacity - 1) {
printf("Stack overflow\n");
return;
}
stack->items[++stack->top] = item;
}
double pop(Stack *stack) {
if (stack->top == -1) {
printf("Stack underflow\n");
return 0;
}
return stack->items[stack->top--];
}
bool is_empty(Stack *stack) {
return stack-1;
}
double calculate_value(Stack *operators, Stack *operands, char op) {
double operand2, result;
switch(op) {
case '+':
operand2 = pop(operands);
result = pop(operands) + operand2;
push(operands, result);
break;
case '-':
operand2 = pop(operands);
result = pop(operands) - operand2;
push(operands, result);
break;
case '*':
operand2 = pop(operands);
result = pop(operands) * operand2;
push(operands, result);
break;
case '/':
if (pop(operands) != 0) {
operand2 = pop(operands);
result = pop(operands) / operand2;
push(operands, result);
} else {
printf("Division by zero error\n");
return 0;
}
break;
default:
printf("Invalid operator\n");
return 0;
}
return result;
}
int main() {
Stack *operands = create_stack(10);
Stack *operators = create_stack(10);
// 用户输入操作数和运算符
while (!is_empty(operands)) {
char input[50];
scanf("%s", input);
if (*input == '+' || *input == '-' || *input == '*' || *input == '/') {
double num = atof(input); // 转换字符串到浮点数
push(operands, num);
} else {
double op = calculate_value(operators, operands, input[0]);
if (op != 0) {
push(operators, op);
} else {
// 处理错误情况
}
}
getchar(); // 消耗掉回车符
}
// 输出结果
if (!is_empty(operands)) {
printf("Final result: %.2f\n", pop(operands));
} else {
printf("No valid expression provided.\n");
}
// 清理栈
while (!is_empty(operands)) {
pop(operands);
}
while (!is_empty(operators)) {
pop(operators);
}
free(operands);
free(operators);
return 0;
}
```
这个程序会读取用户输入的一串四则运算表达式,逐个处理其中的操作数和运算符,并按照栈的原则计算最终结果。注意,此代码仅作为示例,实际应用中需要更完善的错误处理和用户交互界面。
阅读全文