C语言表达式计算器
为了方便了解流程,在程序中把计算过程也输出了.而且栈操作的实现部分也是自己实现的.3sK)g{yvZ(_程序用两个栈,optr寄存运算符,opnd寄存操作数和运算结果.输入的表达式以等号结束,例如:2*(1+2)=
/**************表达式计算器************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>r t!~O(g y;g
#include <conio.h>5V)Nl#E2@b(CC^4D
#include <malloc.h>F6^hwbS
#define STACK_SIZE 100
#define APPEND_SIZE 10
'Hw~K NM*D
struct SNode{
float data; /*存放操作数或者计算结果*/!N,X/x}Qz
char ch; /*存放运算符*/r'?5^hd
};"hDQvOQ/C-`2Z"]
struct Stack{Y:`3clpU9n,P
SNode *top;
SNode *base;
int size;p$xi7?]1MT/C
};
/*栈操作函数*/
int InitStack(Stack &S); /*创建栈*/Av:C#Oww&b W z
int DestroyStack(Stack &S); /*销毁栈*/
int ClearStack(Stack &S); /*清空栈*/
int GetTop(Stack S, SNode &e); /*取出栈顶结点并返回节点值*/GP$_ ~(n3zE
int Push(Stack &S,SNode e); /*将结点e压入栈*/U)f+Y.s4H(]?
int Pop(Stack &S,SNode &e); /*删除栈顶结点并返回其节点值*/
/*表达式计算器相关函数*/1n:UC W1l&i9V
char get_precede(char s,char c); /*判断运算符s和c的优先级*/*e2xj*d[
int isOpr(char c); /*判断输入的字符是不是运算符,是则返回0,否返回1*/t(Z)Ud1ImR
float operate(float x, char opr, float y); /*计算x和y经过运算符opr计算后的结果*/6d \N,}Lr
float compute(); /*表达式结算器主函数*/V$hK)G(kb4`"[8|
char *killzero(float result); /*去掉结果后面的0*/ "\m J'_]o9PQ"G
Hr%sz!o.WO9Pn8E
int InitStack(Stack &S)c5]:\R i G-l?*c e
{
S.base=(SNode *)malloc(STACK_SIZE * sizeof(struct SNode));
if(S.base==NULL)
{
printf("动态分配内存失败!");
return -1;
}
S.top=S.base;0CV'[`H
S.size=STACK_SIZE;
return 0;
}
int DestroyStack(Stack &S)'j5K$sUBu^
{
free(S.base);
return 0;
}
int ClearStack(Stack &S),hl_*zW-n%n
{
S.top=S.base;k3^4]Tk!\sVb&k/H.G
return 0;-t]L |#C uY:s
}
int GetTop(Stack S,SNode &e)p U zfw ZmQ
{t8X{"]+o_8I&hd
if(S.top==S.base)5@9v6J2] us
{
printf("栈以为空!");
return -1;;[s1s\Rx
}