用c++栈写一个计算器
时间: 2024-02-18 16:30:48 浏览: 135
用c++栈写的计算器
4星 · 用户满意度95%
以下是一个基于栈的计算器实现,使用C语言编写。
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_STACK_SIZE 100
typedef enum {
OPERATOR,
OPERAND
} Type;
typedef struct {
Type type;
union {
char operator;
int operand;
};
} Token;
typedef struct {
Token stack[MAX_STACK_SIZE];
int top;
} Stack;
void push(Stack *stack, Token token) {
if (stack->top == MAX_STACK_SIZE) {
fprintf(stderr, "Error: Stack overflow\n");
exit(EXIT_FAILURE);
}
stack->stack[stack->top++] = token;
}
Token pop(Stack *stack) {
if (stack->top == 0) {
fprintf(stderr, "Error: Stack underflow\n");
exit(EXIT_FAILURE);
}
return stack->stack[--stack->top];
}
Token peek(Stack *stack) {
if (stack->top == 0) {
fprintf(stderr, "Error: Stack underflow\n");
exit(EXIT_FAILURE);
}
return stack->stack[stack->top - 1];
}
int is_operator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
int precedence(char c) {
switch (c) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}
int evaluate(int a, int b, char operator) {
switch (operator) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
default:
fprintf(stderr, "Error: Invalid operator\n");
exit(EXIT_FAILURE);
}
}
int main() {
Stack stack;
stack.top = 0;
char input[256];
printf("Enter an expression: ");
fgets(input, 256, stdin);
int length = strlen(input);
if (input[length - 1] == '\n') {
input[length - 1] = '\0';
}
char *ptr = input;
while (*ptr != '\0') {
if (isdigit(*ptr)) {
Token token;
token.type = OPERAND;
token.operand = strtol(ptr, &ptr, 10);
push(&stack, token);
} else if (is_operator(*ptr)) {
while (stack.top > 0 && peek(&stack).type == OPERATOR && precedence(peek(&stack).operator) >= precedence(*ptr)) {
Token operator_token = pop(&stack);
Token operand_token_2 = pop(&stack);
Token operand_token_1 = pop(&stack);
Token result_token;
result_token.type = OPERAND;
result_token.operand = evaluate(operand_token_1.operand, operand_token_2.operand, operator_token.operator);
push(&stack, result_token);
}
Token token;
token.type = OPERATOR;
token.operator = *ptr;
push(&stack, token);
ptr++;
} else {
fprintf(stderr, "Error: Invalid character '%c'\n", *ptr);
exit(EXIT_FAILURE);
}
}
while (stack.top > 1) {
Token operator_token = pop(&stack);
Token operand_token_2 = pop(&stack);
Token operand_token_1 = pop(&stack);
Token result_token;
result_token.type = OPERAND;
result_token.operand = evaluate(operand_token_1.operand, operand_token_2.operand, operator_token.operator);
push(&stack, result_token);
}
Token result_token = pop(&stack);
if (stack.top != 0 || result_token.type != OPERAND) {
fprintf(stderr, "Error: Invalid expression\n");
exit(EXIT_FAILURE);
}
printf("Result: %d\n", result_token.operand);
return 0;
}
```
使用示例:
```
Enter an expression: 3+4*5
Result: 23
```
该计算器实现支持基本的四则运算,并且支持运算符优先级。在实现中,我们使用了一个栈来存储操作数和运算符,并且在遍历输入表达式时,根据当前字符的类型进行不同的处理,以达到计算表达式的目的。
阅读全文