C语言表达式计算器
为了方便了解流程,在程序中把计算过程也输出了.而且栈操作的实现部分也是自己实现的.ur*ji(S/|?G"Ub'rU程序用两个栈,optr寄存运算符,opnd寄存操作数和运算结果.输入的表达式以等号结束,例如:2*(1+2)=O.ZAL%C4n { Y^4{w
/**************表达式计算器************/2H[+H,P/M!r:E
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>W `FR3S
#include <malloc.h>3JYl2h8M
j^9r,RN(SR
#define STACK_SIZE 100
#define APPEND_SIZE 10
.Zdfp;}-x8[P!?
struct SNode{
float data; /*存放操作数或者计算结果*/
char ch; /*存放运算符*/3P%N`8P*{[
};L IL2fF
B/].Qd v
struct Stack{FMTcQZZ
SNode *top;8`0LGs3w'b/w+l'c
SNode *base;|t~~0O&X d
int size;V$T0]SJRd.N
};
UE ]E,_y
/*栈操作函数*/B;aT)K2U
int InitStack(Stack &S); /*创建栈*/$kH'i2SJC6j
int DestroyStack(Stack &S); /*销毁栈*/-a9gZ$F+Ih
int ClearStack(Stack &S); /*清空栈*/^5j0bie3a2g}&L5M
int GetTop(Stack S, SNode &e); /*取出栈顶结点并返回节点值*/^s ~Jz"E(^X
int Push(Stack &S,SNode e); /*将结点e压入栈*/
int Pop(Stack &S,SNode &e); /*删除栈顶结点并返回其节点值*/aqu!Y5} M5b']
b6g ?2sqD&EQ
/*表达式计算器相关函数*/,V J*nC;X*|YE
char get_precede(char s,char c); /*判断运算符s和c的优先级*/7N!f8P.JOZ
int isOpr(char c); /*判断输入的字符是不是运算符,是则返回0,否返回1*/
float operate(float x, char opr, float y); /*计算x和y经过运算符opr计算后的结果*/
float compute(); /*表达式结算器主函数*/5rAj)XRy
char *killzero(float result); /*去掉结果后面的0*/ 5}O;x2tGj+J
int InitStack(Stack &S)Zq7uf/dAy
{
S.base=(SNode *)malloc(STACK_SIZE * sizeof(struct SNode));
if(S.base==NULL)(\/G+y%]\ t D_)F
{
printf("动态分配内存失败!");
return -1;
}V4@/{1L2H)l)@:xw
S.top=S.base;q~ Z]6H"^
S.size=STACK_SIZE;&i5N.}a5l?
return 0;U~s.bi#\ O6?^
}
int DestroyStack(Stack &S)9v"Y_f&u7v6q
{4VMsGNr
free(S.base);|8~.[_:Y5a(Mh%b
return 0;
}