C语言表达式计算器
为了方便了解流程,在程序中把计算过程也输出了.而且栈操作的实现部分也是自己实现的.U7y9SV'F,^o"j[程序用两个栈,optr寄存运算符,opnd寄存操作数和运算结果.输入的表达式以等号结束,例如:2*(1+2)=5nM5Bq_7vd&?
/**************表达式计算器************/b&ha0E;k,\S8j
#include <stdio.h>+^Nh#S7T*g.E
#include <stdlib.h>.N,Kg a0x
#include <string.h> VM [4S g4rF
#include <conio.h>
#include <malloc.h>
#define STACK_SIZE 100C0x!n ?8W)s!]\
#define APPEND_SIZE 10d(a/R{-['oW
struct SNode{
float data; /*存放操作数或者计算结果*/3CH8~+fN.bsH#`
char ch; /*存放运算符*/ws3|1k g0{ZPS%Z
};
struct Stack{
SNode *top;
SNode *base;
int size;
};I0O}_,]7G g Y*ax
~n(L NI)YFsdZ C
/*栈操作函数*/j _&S)~&b Q~vZ9k
int InitStack(Stack &S); /*创建栈*/CmLc&{ P.@w eM.[
int DestroyStack(Stack &S); /*销毁栈*/K)j+bA/q
int ClearStack(Stack &S); /*清空栈*/
int GetTop(Stack S, SNode &e); /*取出栈顶结点并返回节点值*/
int Push(Stack &S,SNode e); /*将结点e压入栈*/O't7@Vf
int Pop(Stack &S,SNode &e); /*删除栈顶结点并返回其节点值*/
/*表达式计算器相关函数*/y9Y%M ~3y.N)f
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(); /*表达式结算器主函数*/1[E^#aws5z
char *killzero(float result); /*去掉结果后面的0*/
H3g3w R2\Pl_&V
int InitStack(Stack &S)
{
S.base=(SNode *)malloc(STACK_SIZE * sizeof(struct SNode));
if(S.base==NULL)
{STt$L {{S;M
printf("动态分配内存失败!");