逆波兰表达式思想下的计算器

来源:互联网 发布:淘宝做工问题退货规则 编辑:程序博客网 时间:2024/05/02 03:56

K&R C Bible《C Programming Language》中采用reverse Polish notation思想的计算器代码:

calc.h

 #define NUMBER '0'
void push(double);
double pop(void);
int getop(char []);
int getch(void);
void ungetch(int);

……………………………………………………………………………………………………………………………………………………………………………………………………………

main.c

#include<stdio.h>
#include<stdlib.h>         /*for atof() */

#define MAXOP 100       /* max size of operand or operator*/
#define  NUMBER '0'      /*signal that a number  was found*/

int getop(char []);
void push(double);
double  pop(void);

/*reverse Polish calculator*/
main()
{
 int type;
 double op2;
 char s[MAXOP];
 
 while((type = getop(s))!= EOF){
  switch(type){
  case NUMBER:
   push(atof(s));
   break;
  case '+':
   push(pop() +pop());
   break;
  case '*':
   push(pop() + pop());
   break;
  case '-':
   op2 = pop();
   push(pop() - op2);
   break;
  case '/':
   op2 = pop();
   if(op2 != 0.0)
    push(pop() / op2);
   else
    printf("error:zero divisor\n");
   break;
  case '\n':
   printf("\t%.8g\n",pop());
   break;
  default:
   printf("errro:unknown command%s\n",s);
   break;
  }
 }
 return 0;
}
……………………………………………………………………………………………………………………………………………………………………………………………………………

stack.c

#include<stdio.h>
#include"calc.h"

#define MAXVAL  100

int sp = 0;
double val[MAXVAL];

void push(double f)
{
    if(sp < MAXVAL)
        val[sp++] = f;
     else
        printf("error:stack full ,can't push %g\n",f);
}

double pop(void)
{
    if(sp > 0)
        return val[--sp];
     else{
        printf("error:stack empty\n");
        return 0.0;
     }
}
 

 

……………………………………………………………………………………………………………………………………………………………………………………………………………
getop.c

#include<ctype.h>
#include<stdio.h>
#include"calc.h"

int getch(void);
void ungetch(int);

/*getop: get  next operator or numberic operand */
int getop(char s[])
{
    int i,c;
   
    while((s[0] = c = getch()) ==' ' || c == '\t')
        ;
     s[1] = '\0';
     if( ! isdigit(c) && c != '.')
        return c;            /*not a number*/
     i = 0;
     if(isdigit(c))           /*collect interger part*/
        while(isdigit(s[++i] = c = getch()))
            ;
     if(c == '.')            /*collect fraction part*/
        while(isdigit(s[++i] = c = getch()))
            ;
     s[i] = '\0';
     if(c != EOF)
        ungetch(c);
     return NUMBER;
}

…………………………………………………………………………………………………………………………………………………………………………………………………………

getch.c

#include<stdio.h>
#define BUFSIZE 100

char buf[BUFSIZE];
int bufp = 0;

int getch(void)
{
    return(bufp > 0) ? buf[--bufp]:getchar();
}

void ungetch(int c)
{
    if(bufp >= BUFSIZE)
        printf("ungetch:too many characters\n");
     else
        buf[bufp++] = c;
}

 上述代码为K&R的C BIBLE书籍中的源代码,经过编译运行,完全正确。不过要注意的是,想要能够正确运行此计算器,必须了解reverse Polish notation.

在此仅作简单叙述:

如要计算3 +4 ,则输入时应为:3 4 +。注意每个字符之间是有空格的,作为一个完整输入的区分。否则无法辨认是34还是3、4。

原创粉丝点击