逆波兰计算器的C完整C代码(输入须为后缀表达式)

来源:互联网 发布:化妆刷 知乎 编辑:程序博客网 时间:2024/05/09 02:14
/* 逆波兰计算器 */#include<stdio.h>#include<stdlib.h>#include<string.h>#include<ctype.h>typedef double Elemtype;typedef struct StackNode {Elemtype data;struct StackNode *next;}StackNode, *pStackNode;typedef struct LinkStack {pStackNode top;int count;}LinkStack, *pLinkStack;//链栈创建和初始化pLinkStack InitStack ( void ){pLinkStack s = (pLinkStack)malloc(sizeof(LinkStack));s -> top = NULL;s -> count = 0;return s;}//链栈是否为空int StackEmpty( pLinkStack s ){return (s -> top == NULL ? 1 : 0 );}//链栈入栈void Push( pLinkStack s, Elemtype e ){pStackNode p = (pStackNode)malloc(sizeof(StackNode));p -> data = e;if( s -> top != NULL )  p -> next = s -> top;s -> top = p;s -> count++;}//链栈出栈Elemtype Pop( pLinkStack s ){Elemtype temp;pStackNode p;if( StackEmpty(s) )exit(0);temp = s -> top -> data;p = s -> top;s->top = s->top->next;free(p);s->count--;return temp;}int main(){char c;Elemtype temp1, temp2;char str[20];int i=0;pLinkStack s = InitStack();printf("请输入表达式 :\n");scanf("%c", &c);while( c != '\n' ) {while( isdigit(c) || c=='.' ) {//过滤数字str[i++] = c;str[i] = '\0';if( i>=20 )printf("出错: 输入的数据过大!\n");scanf("%c", &c);if( c == ' ' ) {Push( s, atof(str));i = 0;break;}}switch( c ) {case '+':temp1 = Pop( s ) ;temp2 = Pop( s ) ;Push( s, temp2 + temp1 );break;case '-':temp1 = Pop( s ) ;temp2 = Pop( s ) ;Push( s, temp2 - temp1);break;case '*':temp1 = Pop( s ) ;temp2 = Pop( s ) ;Push( s, temp2 * temp1);break;case '/':temp1 = Pop( s ) ;temp2 = Pop( s ) ;Push( s, temp2 / temp1);break;default:break;}scanf("%c", &c);}printf("结果为: %f\n", Pop(s));return 0;}

0 0
原创粉丝点击