栈实现非负整数四则运算计算器,写出c++代码
时间: 2023-10-26 08:06:57 浏览: 58
好的,以下是栈实现非负整数四则运算计算器的 C 代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define STACK_SIZE 100 // 定义栈的大小
// 定义栈结构体
typedef struct {
int items[STACK_SIZE]; // 栈元素
int top; // 栈顶指针
} Stack;
// 初始化栈
void initStack(Stack *s) {
s->top = -1;
}
// 判断栈是否为空
int isEmpty(Stack *s) {
return s->top == -1;
}
// 判断栈是否已满
int isFull(Stack *s) {
return s->top == STACK_SIZE - 1;
}
// 入栈操作
void push(Stack *s, int num) {
if (isFull(s)) {
printf("栈已满,无法入栈。\n");
exit(1);
}
s->items[++(s->top)] = num;
}
// 出栈操作
int pop(Stack *s) {
if (isEmpty(s)) {
printf("栈为空,无法出栈。\n");
exit(1);
}
return s->items[(s->top)--];
}
// 获取栈顶元素
int peek(Stack *s) {
return s->items[s->top];
}
// 计算表达式的值
int calculate(char *expr) {
int i = 0, num = 0;
Stack numStack, opStack;
char c, op;
initStack(&numStack); // 初始化数字栈
initStack(&opStack); // 初始化操作符栈
while (expr[i] != '\0') {
c = expr[i];
if (isdigit(c)) { // 如果是数字
num = num * 10 + (c - '0');
if (!isdigit(expr[i+1])) { // 下一个字符不是数字,则表示数字已经结束
push(&numStack, num); // 将数字入栈
num = 0; // 将 num 置为零,用于下一个数字的计算
}
} else if (c == '+' || c == '-') { // 如果是加或减
if (isEmpty(&opStack)) { // 操作符栈为空,直接入栈
push(&opStack, c);
} else {
while (!isEmpty(&opStack) && peek(&opStack) != '(') { // 将所有高优先级的操作符出栈
op = pop(&opStack);
num = pop(&numStack);
if (op == '+') { // 执行加法操作
push(&numStack, pop(&numStack) + num);
} else { // 执行减法操作
push(&numStack, pop(&numStack) - num);
}
}
push(&opStack, c); // 将当前操作符入栈
}
} else if (c == '*' || c == '/') { // 如果是乘或除
if (isEmpty(&opStack) || peek(&opStack) == '+' || peek(&opStack) == '-') {
// 操作符栈为空或栈顶为低优先级操作符,直接入栈
push(&opStack, c);
} else {
// 将所有高优先级的操作符出栈
while (!isEmpty(&opStack) && (peek(&opStack) == '*' || peek(&opStack) == '/')) {
op = pop(&opStack);
num = pop(&numStack);
if (op == '*') { // 执行乘法操作
push(&numStack, pop(&numStack) * num);
} else { // 执行除法操作
push(&numStack, pop(&numStack) / num);
}
}
push(&opStack, c); // 将当前操作符入栈
}
} else if (c == '(') { // 如果是左括号,直接入栈
push(&opStack, c);
} else if (c == ')') { // 如果是右括号
while (!isEmpty(&opStack) && peek(&opStack) != '(') {
// 将所有括号内的操作符出栈
op = pop(&opStack);
num = pop(&numStack);
if (op == '+') { // 执行加法操作
push(&numStack, pop(&numStack) + num);
} else { // 执行减法操作
push(&numStack, pop(&numStack) - num);
}
}
pop(&opStack); // 将左括号出栈
}
i++;
}
// 将剩余的操作符出栈
while (!isEmpty(&opStack)) {
op = pop(&opStack);
num = pop(&numStack);
if (op == '+') { // 执行加法操作
push(&numStack, pop(&numStack) + num);
} else if (op == '-') { // 执行减法操作
push(&numStack, pop(&numStack) - num);
} else if (op == '*') { // 执行乘法操作
push(&numStack, pop(&numStack) * num);
} else if (op == '/') { // 执行除法操作
push(&numStack, pop(&numStack) / num);
}
}
return pop(&numStack); // 返回最终的结果
}
int main() {
char expr[100];
printf("请输入表达式:\n");
scanf("%s", expr);
printf("结果为:%d\n", calculate(expr));
return 0;
}
```
以上是栈实现非负整数四则运算计算器的 C 代码,使用方法为输入一个表达式并回车即可得到计算结果。