C语言表达式计算器
为了方便了解流程,在程序中把计算过程也输出了.而且栈操作的实现部分也是自己实现的.;Bs%V8S#l0Jr!]:G c程序用两个栈,optr寄存运算符,opnd寄存操作数和运算结果.输入的表达式以等号结束,例如:2*(1+2)=
/**************表达式计算器************/
#include <stdio.h>*f|&l1Jm
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <malloc.h>Q1E%fLB ~pekW
e)C$Ar_B
#define STACK_SIZE 1008k3P7{!MHu-`R
#define APPEND_SIZE 10
struct SNode{+Bgfqnk-s XT
float data; /*存放操作数或者计算结果*/
char ch; /*存放运算符*/V3fANyC/H
};$v+U^:Lg,s_1k(h-u [
0?,D/Z(^Z/cI
struct Stack{
SNode *top;
SNode *base;}C-`&w`
int size;Kq&@}:ap*pN
};/TzDs(iJj3Avx
/*栈操作函数*/IV+]`&G*r6X$[t)V
int InitStack(Stack &S); /*创建栈*/.s4Ij-~~b?
int DestroyStack(Stack &S); /*销毁栈*/#P Rb_`
int ClearStack(Stack &S); /*清空栈*/
int GetTop(Stack S, SNode &e); /*取出栈顶结点并返回节点值*/s$s}%GmcDD
int Push(Stack &S,SNode e); /*将结点e压入栈*/
int Pop(Stack &S,SNode &e); /*删除栈顶结点并返回其节点值*/
/*表达式计算器相关函数*/D X*PDeqA*{A
char get_precede(char s,char c); /*判断运算符s和c的优先级*/1`1q`*H'V0q
int isOpr(char c); /*判断输入的字符是不是运算符,是则返回0,否返回1*/
float operate(float x, char opr, float y); /*计算x和y经过运算符opr计算后的结果*/
float compute(); /*表达式结算器主函数*/T~7P F(qP8wE6_
char *killzero(float result); /*去掉结果后面的0*/
int InitStack(Stack &S)
{
S.base=(SNode *)malloc(STACK_SIZE * sizeof(struct SNode));
if(S.base==NULL)2r Vs&kHkJi1M2I
{^-a Fh&Kb1z(@
printf("动态分配内存失败!");
return -1;VJ z.T3W:b
}9@:RIHlY7KA
S.top=S.base;)} HO+gtG@
S.size=STACK_SIZE;0k#Z2V^6\;r+P1Y@
return 0;fnd8`7?!|]/@Im!t
}
eI$g R(V#lo3K5C
int DestroyStack(Stack &S)