简单的计算器
[cpp]
<p> 有很近没看了,也望的差不多了。贴上代码做个记忆吧。</p><p> stack.h</p> #define NULL 0
typedef union
{
double data;
char symbol;
}ElementType;
typedef struct
{
ElementType *pbuffer;
int max;
int top;
}Stack;
Stack *InitStack(int n);
int Push(Stack *sp,ElementType *pdata);
int Pop(Stack *sp,ElementType *pdata);
int DestroyStack(Stack *sp);
int IsEmpty(Stack *sp);
int IsFull(Stack *sp);
int TravereStack(Stack *sp,int (*pfn)(ElementType *pdata));
stack.c
[cpp]
#include "stack.h"
#include <malloc.h>
#include <stdio.h>
#include <string.h>
Stack *InitStack(int n)
{
Stack *sp = NULL;
sp = (Stack *)malloc(sizeof(Stack));
if(!sp)
{
return sp;
}
sp->pbuffer = (ElementType *)malloc(sizeof(ElementType)*n);
if(!sp->pbuffer)
{
free(sp);
sp=NULL;
return sp;
}
sp->max = n;
sp->top = -1;
return sp;
}
int Push(Stack *sp,ElementType *pdata)
{
if(IsFull(sp))
{
return 0;
}
sp->top++;
//sp->pbuffer[sp->top] = *pdata;
memcpy(sp->pbuffer + sp->top,pdata,sizeof(ElementType));
return 1;
}
int Pop(Stack *sp,ElementType *pdata)
{
if(IsEmpty(sp))
{
return 0;
}
*pdata = sp->pbuffer[sp->top];
sp->top--;
return 1;
}
int DestroyStack(Stack *sp)
{
if(sp)
{
free(sp->pbuffer);
free(sp);
return 1;
}
return 0;
}
int IsEmpty(Stack *sp)
{
return sp->top == -1;
}
int IsFull(Stack *sp)
{
return sp->top == sp->max;
}
int TravereStack(Stack *sp,int (*pfn)(ElementType *pdata))
{
int i =0;
for(i=0;i<sp->top+1;i++)
{
pfn(sp->pbuffer+i);
}
printf("\n");
return 1;
}
主要实现的代码:
[cpp]
#include "stack.h"
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct
{
Stack *spdata;
Stack *spsymbol;
int total;
}Cal;
int SignTab[7][7] = {
// + - * / ( ) #
/* + */ 1, 1, -1, -1, -1, 1, 1,
/* - */ 1, 1, -1, -1, -1, 1, 1,
/* * */ 1, 1, 1, 1, -1, 1, 1,
/* / */ 1, 1, 1, 1, -1, 1, 1,
/* ( */ -1, -1, -1, -1, -1, 0, 2,
/* ) */ 1, 1, 1, 1, 1, 1, 1,
/* # */ -1, -1, -1, -1, -1, 2, 0
};
Cal *InitCal(int n)
{
int i =0;
Cal *cal = (Cal *)malloc(sizeof(Cal));
if(!cal)
{
return cal;
}
cal->total = n;
cal->spdata = InitStack(cal->total);
if(!cal->spdata)
{
free(cal);
return cal;
}
cal->spsymbol = InitStack(cal->total);
if(!cal->spsymbol)
{
free(cal);
return cal;
}
return cal;
}
char * GetStr()
{
int i =0;
char *str = (char *)malloc(sizeof(char)*20);
printf("请输入计算表达式:");
gets(str);
while(*(str+i))
{
i++;
}
补充:软件开发 , C++ ,