C语言表达式计算器
为了方便了解流程,在程序中把计算过程也输出了.而且栈操作的实现部分也是自己实现的.&j!H[ l5c7d1j程序用两个栈,optr寄存运算符,opnd寄存操作数和运算结果.输入的表达式以等号结束,例如:2*(1+2)=f"w[c#PH ZW
/**************表达式计算器************/'wud`$eD+Dx%r9?
#include <stdio.h>p v@Upz-~.r
#include <stdlib.h>mJrc?
#include <string.h>`!vob#]6Y
#include <conio.h>
#include <malloc.h>pt!C.q)pZN{
(Ivnd fn^
#define STACK_SIZE 100
#define APPEND_SIZE 10
.^:ub^z Ua4D
struct SNode{mD}(@s
float data; /*存放操作数或者计算结果*/%a*U+D!J,}l*vAh
char ch; /*存放运算符*/xGpH-|#T}
};
]nZb:n"W
struct Stack{
SNode *top;
SNode *base;Xa6\%@k6sr/r @3j?:?
int size;
};
/*栈操作函数*/
int InitStack(Stack &S); /*创建栈*/
int DestroyStack(Stack &S); /*销毁栈*/(`a[-c*lc^RHrQa
int ClearStack(Stack &S); /*清空栈*/r VY7R ^gF
int GetTop(Stack S, SNode &e); /*取出栈顶结点并返回节点值*/X&[I |?/H:z6{Y
int Push(Stack &S,SNode e); /*将结点e压入栈*/)^d`.O:A
int Pop(Stack &S,SNode &e); /*删除栈顶结点并返回其节点值*/
/*表达式计算器相关函数*/
char get_precede(char s,char c); /*判断运算符s和c的优先级*/w1eXo6e }:L
int isOpr(char c); /*判断输入的字符是不是运算符,是则返回0,否返回1*/2wfK1l7@C BL
float operate(float x, char opr, float y); /*计算x和y经过运算符opr计算后的结果*/i"w5p3u9m7s/f.i ne |1S
float compute(); /*表达式结算器主函数*/&y7K&E6{wc-f
char *killzero(float result); /*去掉结果后面的0*/
A9n|7Cj3isx&j
int InitStack(Stack &S)
{
S.base=(SNode *)malloc(STACK_SIZE * sizeof(struct SNode));
if(S.base==NULL) lVq0@%IHif
{2ijs`O LQ
printf("动态分配内存失败!");
return -1;m4D2lEc1m
}
S.top=S.base;
S.size=STACK_SIZE;
return 0; dy^t$`1iR@
}