用C语言写一个可以处理括号内运算的四则运算计算器
时间: 2023-11-20 12:06:51 浏览: 80
带括号四则运算器
好的,以下是一个可以处理括号内运算的四则运算计算器的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
#define MAXBUFFER 10
typedef struct
{
double *base;
double *top;
int stacksize;
} Stack;
void InitStack(Stack *S)
{
S->base = (double *)malloc(STACK_INIT_SIZE * sizeof(double));
if (!S->base)
exit(0);
S->top = S->base;
S->stacksize = STACK_INIT_SIZE;
}
void Push(Stack *S, double e)
{
if (S->top - S->base >= S->stacksize)
{
S->base = (double *)realloc(S->base, (S->stacksize + STACKINCREMENT) * sizeof(double));
if (!S->base)
exit(0);
S->top = S->base + S->stacksize;
S->stacksize += STACKINCREMENT;
}
*(S->top) = e;
S->top++;
}
void Pop(Stack *S, double *e)
{
if (S->top == S->base)
return;
*e = *(--S->top);
}
double GetTop(Stack *S)
{
if (S->top != S->base)
return *(S->top - 1);
return 0;
}
int StackEmpty(Stack *S)
{
if (S->top == S->base)
return 1;
else
return 0;
}
int OperatorPriority(char op)
{
switch (op)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '(':
return 0;
}
return -1;
}
double Calculate(double a, char op, double b)
{
switch (op)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
}
return 0;
}
double EvaluateExpression(char *exp)
{
Stack numStack;
Stack opStack;
double num = 0;
char buffer[MAXBUFFER];
int i = 0;
InitStack(&numStack);
InitStack(&opStack);
while (*exp != '\0')
{
if (isdigit(*exp) || *exp == '.')
{
buffer[i++] = *exp;
if (i >= MAXBUFFER)
exit(0);
}
else if (*exp == '+' || *exp == '-' || *exp == '*' || *exp == '/')
{
buffer[i] = '\0';
num = atof(buffer);
i = 0;
while (!StackEmpty(&opStack) && OperatorPriority(*exp) <= OperatorPriority(GetTop(&opStack)))
{
double b, a;
Pop(&numStack, &b);
Pop(&numStack, &a);
Pop(&opStack, &opStack);
Push(&numStack, Calculate(a, opStack, b));
}
Push(&opStack, *exp);
}
else if (*exp == '(')
{
Push(&opStack, *exp);
}
else if (*exp == ')')
{
buffer[i] = '\0';
num = atof(buffer);
i = 0;
while (!StackEmpty(&opStack) && GetTop(&opStack) != '(')
{
double b, a;
Pop(&numStack, &b);
Pop(&numStack, &a);
Pop(&opStack, &opStack);
Push(&numStack, Calculate(a, opStack, b));
}
if (GetTop(&opStack) == '(')
{
Pop(&opStack, &opStack);
}
}
exp++;
}
buffer[i] = '\0';
num = atof(buffer);
while (!StackEmpty(&opStack))
{
double b, a;
Pop(&numStack, &b);
Pop(&numStack, &a);
Pop(&opStack, &opStack);
Push(&numStack, Calculate(a, opStack, b));
}
if (!StackEmpty(&numStack))
{
double result;
Pop(&numStack, &result);
return result;
}
return 0;
}
int main()
{
char exp[100];
printf("请输入四则运算表达式:");
gets(exp);
printf("结果为:%f", EvaluateExpression(exp));
return 0;
}
```
这个计算器可以处理带有括号的四则运算表达式,支持加、减、乘、除和小数点。当然,还有很多可以改进和优化的地方,比如错误处理、表达式合法性检查等,但这里只是一个简单的演示,供参考。
阅读全文