#include
#include
#define N 100
char stack1[N];
char stack2[N];
int top = -1;
char pop(char *stack)
{
char tmp;
if(top == -1)
{
printf("该栈为空!\n");
}
else
{
tmp = stack[top];
top--;
}
return tmp;
}
void push(char *stack,char data)
{
if(top == N-1)
{
printf("该栈已满!\n");
}
else
{
top++;
stack[top] = data;
}
}
char *topostfix(char *expstr) { char *postfix = (char *)malloc(sizeof(char)); int i = 0; int j = 0; int tmp; while(expstr[i] != '\0') { switch(expstr[i]) { case '+': case '-': while(top != -1 && stack1[top] != '(') { postfix[j++] = pop(stack1); } push(stack1,expstr[i++]); break; case '*': case '/': while(top != -1 && (stack1[top] == '*' || stack1[top] == '/')) { postfix[j++] = pop(stack1); } push(stack1,expstr[i++]); break; case '(': push(stack1,expstr[i++]); break; case ')': tmp = pop(stack1); while(top != -1 && tmp != '(') { postfix[j++] = tmp; tmp = pop(stack1); } i++; break; default : while(expstr[i] >= '0' && expstr[i] <= '9' && expstr[i] != '\0') { postfix[j++] = expstr[i++]; } postfix[j++] = ' '; break; } } while(top != -1) { postfix[j++] = pop(stack1); } postfix[j] = '\0'; return postfix; } int operation(char *postfix) { int i = 0; int result; while(postfix[i] != '\0') { if(postfix[i] >= '0' && postfix[i] <= '9') { result = 0; while(postfix[i] != ' ') { result = result * 10 + (postfix[i] - '0'); i++; } i++; push(stack2,result); } else { if(postfix[i] != ' ') { int y = pop(stack2); int x = pop(stack2); switch(postfix[i]) { case '+': result = x + y; break; case '-': result = x - y; break; case '*': result = x * y; break; case '/': result = x / y; break; } push(stack2,result); } i++; } } return result; } int main() { int result; char expstr[N]; char *postfix = (char *)malloc(sizeof(char)); printf("请输入表达式:"); gets(expstr); printf("你输入的表达式为:"); puts(expstr); postfix = topostfix(expstr); printf("你输入的表达式的后缀表达式为:"); puts(postfix); result = operation(postfix); printf("%s=%d\n",expstr,result); return 0; } 本来想实现浮点型的,myatof是写好了,但还有很多困难~~~~遂不大想写了~~ 这个计算器只有+,-,*,/,()~~~~ 给点点你们改的空间,将结果能输出为浮点型~~~~~ 提示:强制类型转换~~~~