#include<stdio.h>
#include<stdlib.h>
#include<math.h>
struct stack{
int capacity;
int topofstack;
double *a;
};
struct stack *createstack(int n){
struct stack *s;
s = (struct stack *)malloc(sizeof(struct stack));
if(s == NULL){
printf("Out of Space!\n");
return NULL;
}
s->capacity = n;
s->a = (double *)malloc(sizeof(double)*n);
if(s->a == NULL){
printf("Out of Space!\n");
return NULL;
}
s->topofstack = -1;
return s;
}
void push(double n,struct stack *s){
if(s->topofstack<s->capacity-1)
s->a[++s->topofstack] = n;
}
double popandtop(struct stack *s){
if(s->topofstack>-1)
return s->a[s->topofstack--];
}
int main(){
struct stack *s;
int i,flag,pointflag;
double num,b,d,tmp1,tmp2;
char ch[80],c;
i = 0;
s = createstack(10); //create stack
while(scanf("%s",ch)){
c = getchar();
i = 0;
num = 0;
pointflag = 0;
if(ch[i]>='0'&&ch[i]<='9'){ //if it's number push into stack
while(ch[i]!='\0'){
if(ch[i] == '.'){ //consider the decimal fraction stituation
pointflag = 1;
i++;
continue;
}
if(pointflag){
num += (ch[i] - '0')*pow(10,-pointflag);
pointflag++;
}
else num = num*10 + ch[i] - '0';
i++;
}
push(num,s);
}
else
switch(ch[i]){ //if it's operation pop two element , after operation push back the result
case '+':push(popandtop(s) + popandtop(s),s);break;
case '-':{ //sbustracion and division has order
tmp1 = popandtop(s);
tmp2 = popandtop(s);
push(tmp2 - tmp1,s);
}break;
case '*':push(popandtop(s) * popandtop(s),s);break;
case '/':{
tmp1 = popandtop(s);
tmp2 = popandtop(s);
push(tmp2 / tmp1,s);
}break;
}
if(c == '\n'||c == '\0')
break;
}
printf("%lf",popandtop(s));
}
利用stack计算后缀表达式
最新推荐文章于 2022-05-30 12:00:03 发布