#include <stdio.h>
#include <stdlib.h>
typedef struct Stack{
char data[10];
int top;
}stack, *sp;
sp createStack(){
sp ptr = malloc(sizeof(stack));
ptr->top = -1;
return ptr;
}
void Push(sp ptr, char c){
ptr->data[++ptr->top] = c;
}
char Pop(sp ptr){
if(ptr->top == -1) return 'w';
return ptr->data[ptr->top--];
}
char Top(sp ptr){
if(ptr->top == -1) return 'w';
return ptr->data[ptr->top];
}
int main(){
char str[50], c, result[50]={'\0'};
scanf("%s",str);
sp ptr1 = createStack(), ptr2 = createStack();
int i=0, j=0;
while(str[i] != '\0'){
c = str[i];
if(c >= '0' && c <= '9') {
result[j] = c;
j++;
}
else{
char temp=Top(ptr2);
if(temp=='w' || c=='(') Push(ptr2, c);
else if((c=='*' || c=='/') && (temp=='+' || temp=='-')) Push(ptr2, c);
else if((c=='*' || c=='/') && (temp=='*' || temp=='/')) {result[j]=Pop(ptr2);Push(ptr2, c);j++;}
else if(c==')'){temp=Pop(ptr2);while(temp!='('){result[j]=temp;j++;temp=Pop(ptr2);}}
else {while(ptr2->top!=-1 && Top(ptr2)!='('){result[j]=Pop(ptr2);j++;}Push(ptr2, c);}
}
i++;
}
while(ptr2->top!=-1){
result[j] = Pop(ptr2);
j++;
}
int h=0, top=-1;
float s[20]={0};
while(result[h] != '\0'){
if(result[h] >= '0' && result[h] <= '9') {s[++top]=result[h]-48;h++;continue;}
if(result[h] == '+'){s[top-1] += s[top];top--;}
else if(result[h] == '-'){s[top-1] -= s[top];top--;}
else if(result[h] == '*'){s[top-1] *= s[top];top--;}
else if(result[h] == '/'){s[top-1] /= s[top];top--;}
h++;
}
printf("%.2f\n",s[0]);
i=0;
while(result[i]!='\0'){
printf("%c ",result[i]);
i++;
}
}
三重雪关扉
最新推荐文章于 2024-06-18 17:54:08 发布