C语言表达式计算器
为了方便了解流程,在程序中把计算过程也输出了.而且栈操作的实现部分也是自己实现的.4|qQ:k3~ q程序用两个栈,optr寄存运算符,opnd寄存操作数和运算结果.输入的表达式以等号结束,例如:2*(1+2)=
/**************表达式计算器************/
#include <stdio.h>.c)kgl;haw-@
#include <stdlib.h>
#include <string.h>i2Sn-z-{MCW&] pM
#include <conio.h> Y9p:A6`$}u*S~
#include <malloc.h>
#define STACK_SIZE 100
#define APPEND_SIZE 10.PWO*?oP4y
struct SNode{9XPr)_!N@
float data; /*存放操作数或者计算结果*/y2H+Xj(WJ
char ch; /*存放运算符*/
};
struct Stack{
SNode *top;
SNode *base;
int size;
};;j;L.X0O5Y5I#D7f
,w8|*g9I,b7G/x v
/*栈操作函数*/
int InitStack(Stack &S); /*创建栈*/
int DestroyStack(Stack &S); /*销毁栈*/)A` x6dy!s}sl
int ClearStack(Stack &S); /*清空栈*/"m.@'eX*fT3`*O
int GetTop(Stack S, SNode &e); /*取出栈顶结点并返回节点值*/
int Push(Stack &S,SNode e); /*将结点e压入栈*/ Uqm x%g?2q
int Pop(Stack &S,SNode &e); /*删除栈顶结点并返回其节点值*/
/*表达式计算器相关函数*/
char get_precede(char s,char c); /*判断运算符s和c的优先级*/xmBq+wF[-Op
int isOpr(char c); /*判断输入的字符是不是运算符,是则返回0,否返回1*/
float operate(float x, char opr, float y); /*计算x和y经过运算符opr计算后的结果*/Pu-fix_O
float compute(); /*表达式结算器主函数*/
char *killzero(float result); /*去掉结果后面的0*/ f.W0T:mi
^ iCtoV(YrC^
int InitStack(Stack &S)'sQ:F5Oic H MG
{!Y4ud8Vm
S.base=(SNode *)malloc(STACK_SIZE * sizeof(struct SNode));
if(S.base==NULL)jnf(i0yj*}H
{
printf("动态分配内存失败!");_]Z Ju%o)M
return -1;
}yH,`2z~Q,|8u
S.top=S.base;
S.size=STACK_SIZE;
return 0;
}
t5[7C'`+v\C.U]4T
int DestroyStack(Stack &S)
{
free(S.base);