用栈stack实现简单计算器 c++
时间: 2023-08-28 07:06:21 浏览: 191
好的,这个问题非常适合用程序解决。以下是用stack实现简单计算器的c代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define STACKLEN 1000 /* 栈的最大容量 */
typedef struct {
int top; /* 栈顶指针 */
double data[STACKLEN]; /* 元素数组 */
} Stack;
void push(Stack *pstack, double value) {
if (pstack->top == STACKLEN - 1) {
printf("Error: stack overflow!\n");
exit(EXIT_FAILURE);
} else {
pstack->data[++pstack->top] = value;
}
}
double pop(Stack *pstack) {
if (pstack->top == -1) {
printf("Error: stack underflow!\n");
exit(EXIT_FAILURE);
} else {
return pstack->data[pstack->top--];
}
}
bool is_digit(char c) {
return (c >= '0' && c <= '9');
}
int precedence(char op) {
if (op == '+' || op == '-') return 1;
else if (op == '*' || op == '/') return 2;
else return 0;
}
double calculate(double left, char op, double right) {
switch (op) {
case '+': return left + right;
case '-': return left - right;
case '*': return left * right;
case '/': return left / right;
default:
printf("Error: invalid operator!\n");
exit(EXIT_FAILURE);
}
}
double eval(char *expr) {
Stack operandStack;
operandStack.top = -1;
Stack operatorStack;
operatorStack.top = -1;
int len = strlen(expr);
int i = 0;
while (i < len) {
char c = expr[i];
if (is_digit(c)) {
double value = 0.0;
while (i < len && is_digit(expr[i])) {
value = value * 10.0 + (double)(expr[i] - '0');
i++;
}
push(&operandStack, value);
} else {
while (operatorStack.top != -1
&& precedence(operatorStack.data[operatorStack.top]) >= precedence(c)) {
char op = operatorStack.data[operatorStack.top--];
double right = pop(&operandStack);
double left = pop(&operandStack);
push(&operandStack, calculate(left, op, right));
}
push(&operatorStack, c);
i++;
}
}
while (operatorStack.top != -1) {
char op = operatorStack.data[operatorStack.top--];
double right = pop(&operandStack);
double left = pop(&operandStack);
push(&operandStack, calculate(left, op, right));
}
return pop(&operandStack);
}
int main() {
char s[1000];
printf("Please enter an expression: ");
scanf("%s", s);
double result = eval(s);
printf("Result: %f\n", result);
return 0;
}
```
这段代码定义了两个栈:一个操作数栈(operandStack)和一个操作符栈(operatorStack),通过不断入栈和出栈的操作,实现对表达式进行求值。其中,is_digit函数用于判断一个字符是否是数字;precedence函数用于比较两个运算符的优先级;calculate函数用于计算两个操作数和一个操作符的运算结果;eval函数是主函数,用于将输入的表达式转化为数字计算结果。
希望这个回答能够帮助您!
阅读全文