用栈实现计算器c语言
时间: 2023-07-13 22:10:48 浏览: 84
以下是用栈实现计算器的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int top;
double data[MAX_SIZE];
} Stack;
void init(Stack *s) {
s->top = -1;
}
int isEmpty(Stack *s) {
return s->top == -1;
}
int isFull(Stack *s) {
return s->top == MAX_SIZE - 1;
}
int push(Stack *s, double x) {
if (isFull(s)) {
return 0;
}
s->top++;
s->data[s->top] = x;
return 1;
}
int pop(Stack *s, double *x) {
if (isEmpty(s)) {
return 0;
}
*x = s->data[s->top];
s->top--;
return 1;
}
int peek(Stack *s, double *x) {
if (isEmpty(s)) {
return 0;
}
*x = s->data[s->top];
return 1;
}
int calculate(double a, double b, char op, double *result) {
switch (op) {
case '+':
*result = a + b;
break;
case '-':
*result = a - b;
break;
case '*':
*result = a * b;
break;
case '/':
if (b == 0) {
return 0;
}
*result = a / b;
break;
default:
return 0;
}
return 1;
}
int main() {
Stack s;
init(&s);
char c;
double x, a, b, result;
while (scanf("%c", &c) != EOF) {
if (c >= '0' && c <= '9') {
ungetc(c, stdin);
scanf("%lf", &x);
push(&s, x);
} else if (c == '+' || c == '-' || c == '*' || c == '/') {
if (pop(&s, &b) && pop(&s, &a)) {
if (calculate(a, b, c, &result)) {
push(&s, result);
} else {
printf("Invalid expression\n");
return 1;
}
} else {
printf("Invalid expression\n");
return 1;
}
} else if (c == '\n') {
if (peek(&s, &result) && isEmpty(&s)) {
printf("%.2f\n", result);
} else {
printf("Invalid expression\n");
return 1;
}
init(&s);
}
}
return 0;
}
```
该程序通过读入一个字符,如果是数字,则将其转换为浮点数并压入栈中;如果是运算符,则从栈中弹出两个数进行相应的运算,并将结果压入栈中;如果是换行符,则输出栈顶元素(即最终结果),并清空栈。在计算过程中,如果栈空或栈顶元素不够两个,则输出错误信息并退出程序。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)