#define_CRT_SECURE_NO_WARNINGS#include<stdio.h>#include<stdlib.h>#include<string.h>#include<ctype.h>#defineMaxOp100#definenumber'0'#defineMaxRowNum100chargetop(char*);voidpush(double);doublepop(void);doublemyatof(char*);intmain(){int argc;char s[MaxOp],*argv[MaxRawNum];double num, op;char**temp = argv;voidungets(char[]);scanf("%d",&argc);for(int i =1; i < argc; i++){
argv[i]=(char*)malloc(MaxRowNum *sizeof(char));scanf("%s", argv[i]);}while(--argc >0){//ungets(" ");ungets(*++temp);//上面运用ungets的目的是想直接读取之前scanf函数捕获到的字符串中//也就是说将它们先放到缓存区buf中,再对其进行读取//而不是用getch中的getchar函数来直接读取输入内容//ungets(" ");该语句是因为每次getop读取数字时,为了确定所读取数字的完整性//所以在每次读取数字之前事先放入一个空格符,这样可以在不读取新的输入内容时//还可以保证getop函数的正常运作//不过在该程序中,该语句可以省略,因为scanf遇到空格符、换行符就会停止读取//也就是说即使是在缓存区中无任何内容,在输入内容中有一个换行符//在第一次读取完数字之后,该换行符就会被压入缓存区//之后它就一直待在缓存区,也就是说不用担心因为多读取字符而导致getop函数无法运行的问题switch(getop(s)){case number:push(atof(s));break;case'+':
num =pop()+pop();push(num);break;case'-':
op =pop();
num =pop()- op;push(num);break;case'*':
num =pop()*pop();push(num);break;case'/':
op =pop();if(op !=0.0){
num =pop()/ op;push(num);}elseprintf("error: zero divisor\n");break;//case '\n':// printf("%f\n", pop());// break; //不需要捕获到换行符之后,再输出内容default:printf("error: unknown command %s\n",s);
argc =1;break;}}printf("\t%.8g\n",pop());return0;}doublemyatof(char*s){int sign;double num, pow;
num =0.0;
pow =1.0;
sign =(*s =='-')?-1:1;while(isdigit(*s)){
num =10.0* num +*s -'0';}if(*s =='.')
s++;while(isdigit(*s)){
num =10.0* num +*s -'0';
pow *=10.0;}
num = sign * num / pow;return num;}#defineMaxVal100double operand[MaxVal];int place =0;voidpush(double op){//注意限定的范围if(place < MaxVal)
operand[place++]= op;else{printf("the stack of operand is full, can't push");return;}}doublepop(void){//注意限定范围if(place >0)return operand[--place];else{printf("the stack is empty,can't pop\n");return0.0;}}chargetch(void);voidungetch(char);chargetop(char*s){char c;while((*s = c =getch())==' '|| c =='\t');*(s+1)='\0';if(!isdigit(c)&& c !='.')return c;if(isdigit(*++s = c =getch()))//整数部分;if(c =='.')while(isdigit(*++s = c =getch()))//小数部分;if(c !=EOF)ungetch(c);*s ='\0';return number;}voidungets(char s[]){voidungetch(char);int len =strlen(s);while(len >0)ungetch(s[--len]);}#defineMaxSize100char buf[MaxSize];char*bufp = buf;//buf的下一个空闲位置chargetch(){return(bufp > buf)?*--bufp :getchar();}voidungetch(char c){if(bufp < buf + MaxSize){*bufp = c;
bufp++;}elseprintf("there is no space in buffer\n");}