注:最主要需要注意的是代码中那个标注的getchar()函数的使用
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define False 0
#define True 1
typedef struct
{
int top;
int maxSize;
double *element;
}Stack;
//创建
void Create(Stack *S,int mSize)
{
S->maxSize = mSize;
S->element = (double*)malloc(sizeof(double)*mSize);
S->top = -1;
}
//销毁
void Destroy(Stack *S)
{
S->maxSize = -1;
free(S->element);
S->top = -1;
}
//判断空
int IsEmpty(Stack *S)
{
return S->top == -1;
}
//判断满
int IsFull(Stack *S)
{
return S->top == S->maxSize;
}
//获取栈顶元素
int Top(Stack *S,double *x)
{
if(IsEmpty(S))
return False;
*x = S->element[S->top];
return True;
}
//向栈顶添加一个元素
int Push(Stack *S,double x)
{
if(IsFull(S))
return False;
S->top++;
S->element[S->top] = x;
return True;
}
//取出栈顶元素
int Pop(Stack *S)
{
if(IsEmpty(S))
return False;
S->top--;
return True;
}
void Clear(Stack *S)
{
S->top = -1;
}
int GetOperands(Stack *S,double *op1,double *op2)
{
if(!Top(S,op1))
{
printf("Missing Operand!");
return False;
}
Pop(S);
if(!Top(S,op2))
{
printf("Missing Operand!");
return False;
}
Pop(S);
return True;
}
void DoOperator(Stack *S,char ope)
{
int result;
double ope1,ope2;
result = GetOperands(S,&ope1,&ope2);
if(!result)
Clear(S);
else
{
switch(ope)
{
case '+':
Push(S,ope2+ope1);
break;
case '-':
Push(S,ope2-ope1);
break;
case '*':
Push(S,ope1*ope2);
break;
case '/':
if(fabs(ope2)<1e-6)
{
printf("Divided by 0!");
Clear(S);
}
else
{
Push(S,ope2/ope1);
}
break;
case '^':
Push(S,pow(ope1,ope2));
break;
}
}
}
int main()
{
Stack S;
Create(&S,10);
char c;
double newop;
scanf("%c",&c);
for(;c!='#';)
{
switch(c)
{
case '+':
case '-':
case '*':
case '/':
case '^':
DoOperator(&S,c);
break;
default:
newop = c-'0';
Push(&S,newop);
}
//要好好理解这个getchar的作用!!!
//它读取的是我们按得回车键!
getchar();
scanf("%c",&c);
}
if(Top(&S,&newop))
printf("%f",newop);
Destroy(&S);
return 0;
}
版权声明:本文为weixin_42394170原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。