C语言表达式计算器
为了方便了解流程,在程序中把计算过程也输出了.而且栈操作的实现部分也是自己实现的.*J O%N PY(~程序用两个栈,optr寄存运算符,opnd寄存操作数和运算结果.输入的表达式以等号结束,例如:2*(1+2)=
/**************表达式计算器************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <malloc.h>
#define STACK_SIZE 100
#define APPEND_SIZE 10
LaB*Q.PvWJ5R
struct SNode{
float data; /*存放操作数或者计算结果*/ ?)Bj,h8lz
char ch; /*存放运算符*/
};1d0Kd3Cav#v
struct Stack{
SNode *top;
SNode *base;
int size;+H O%r(G9p$Y
};
| im-z r2w%my(~?
/*栈操作函数*/
int InitStack(Stack &S); /*创建栈*/.cY+v)y L&Nusxiv
int DestroyStack(Stack &S); /*销毁栈*/
int ClearStack(Stack &S); /*清空栈*/4|R@$i^9l
int GetTop(Stack S, SNode &e); /*取出栈顶结点并返回节点值*/:O'|$}H/J A+h k$J
int Push(Stack &S,SNode e); /*将结点e压入栈*/
int Pop(Stack &S,SNode &e); /*删除栈顶结点并返回其节点值*/
/*表达式计算器相关函数*/f&oH&q7i4k
char get_precede(char s,char c); /*判断运算符s和c的优先级*/
int isOpr(char c); /*判断输入的字符是不是运算符,是则返回0,否返回1*/
float operate(float x, char opr, float y); /*计算x和y经过运算符opr计算后的结果*/
float compute(); /*表达式结算器主函数*/
char *killzero(float result); /*去掉结果后面的0*/
int InitStack(Stack &S)
{^*`y?"q `(@
S.base=(SNode *)malloc(STACK_SIZE * sizeof(struct SNode));1l;~9i&N \JV
if(S.base==NULL)9fw v-p0{[:J$M
{
printf("动态分配内存失败!");"_R A?T_:rw
return -1;
}A(l[2}k/L3o&e
S.top=S.base;
S.size=STACK_SIZE;
return 0;
}w_s-q aI9|2}
]hs:R[;AM!C
int DestroyStack(Stack &S)
{
free(S.base);FG%l(R5~ |5p%U&\5Z
return 0;Qg sv$wVS
}-K*S ~Zo"_}!U
&f`}/V!n2o)f pKh
int ClearStack(Stack &S)}2uoK!G]5yz2I YF
{
S.top=S.base; oIu!v-E.p
return 0;FH8kJ(^(D5q Xo??h
}^5Y?-P6k_
*n,sl }"y3?
int GetTop(Stack S,SNode &e)'E0T~W)g;Bm
{
if(S.top==S.base)
{