|
#define MAX 30
#define ADD 10
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct s{
char *base ;
char *top;
int Ssize;
} AA;
void InitStack(AA *s)//构造栈
{
s->base=(char *)malloc(MAX*sizeof(char));;
if (s->base==NULL) { printf ("内存不足!"); exit (0);}
s->top=s->base;
s->Ssize=MAX;
}
void top(AA *s,char *e)//取函数
{
if (s->top==s->base) { printf ("输入错误!"); exit (0);}
*e=*(s->top-1);
}
void Gettop(AA *s,char *e)//取元素并指针后移
{
if (s->top==s->base) { printf ("输入错误!"); exit (0);}
*e=*(--s->top);
}
void Push(AA *s,char e)//插入元素
{
if ((s->top-s->base)>=s->Ssize) {
s->base=(char *)realloc (s->base,(s->Ssize+ADD)*sizeof (char));
if (s->base==NULL) { printf ("内存不足!"); exit (0);}
s->top=s->base+s->Ssize;
s->Ssize+=ADD;
}
*s->top++=e;
}
int ysdj(char *e)//定义运算符的等级
{
switch (*e){
case '(':
case '#': return 0; break;
case '-':
case '+': return 1; break;
case '*':
case '/': return 2; break;
}
}
main ()
{
AA s1,s2;//操作数//运算符
char input,e,*z;
int i,j,k=1;
double add[20]={20,0};
Loop: printf ("输入的表达式以“#”结尾\n");
InitStack(&s1);
InitStack(&s2);
Push(&s2,'#');
do {
input =getchar ();
if (isdigit(input)) Push(&s1,input);
else if (input==')'||input=='#')
do {
Gettop(&s2,&e);
if (e!='('&&e!='#')
Push(&s1,e);
else if (input!=')')
Push (&s1,input);
}while (e!='('&&e!='#');
else if (input=='+'||input=='-'||input=='*'||input=='/'){
do {
i=ysdj(&input);
top(&s2,&e);
j=ysdj(&e);
if (i<=j){
Gettop(&s2,&e);
Push(&s1,e);
}
}
while (i<=j);
if (i>j)
Push(&s2,input);}
else if (input=='(')Push (&s2,input);
else continue;
}while (input!='#');
z=s1.base;
do {
e=*z;
z+=1;
if (isdigit(e)){
add[k]=e-48;
k++;
}
else {
switch (e){
case '+': add[k-2]=add[k-2]+add[k-1]; break;
case '-': add[k-2]=add[k-2]-add[k-1]; break;
case '*': add[k-2]=add[k-2]*add[k-1]; break;
case '/': add[k-2]=add[k-2]/add[k-1]; break;
}
k--;
}
}while (e!='#'&& k<=20);
printf ("结果是:%.2lf\n",add[1]);
printf ("继续操作输入'y'或退出'n'\n");
fflush(stdin);
scanf ("%c",&e);
if (e=='y'){
system("CLS");free(s1.base);free(s2.base);goto Loop ;}
else
{
free(s1.base);free(s2.base);exit (0);}
} |
|