home *** CD-ROM | disk | FTP | other *** search
/ Between Heaven & Hell 2 / BetweenHeavenHell.cdr / 500 / 401 / calc.sci < prev    next >
Text File  |  1984-08-31  |  2KB  |  101 lines

  1. char *Lineptr;
  2. int Stack[10], Stackptr, Stacktop;
  3.  
  4. calc()
  5. {
  6.    char line[80];
  7.    char c;
  8.  
  9.  
  10.    Stacktop = 10;
  11.    while(1)
  12.    {
  13.       puts("-> ");
  14.       Lineptr = line;
  15.       c = gets( line );
  16.       if(c)
  17.       {
  18.          if( *Lineptr=='x' )
  19.             return;
  20.          addition();
  21.          printf( "%d\n", pop() );
  22.       }
  23.    }
  24. }
  25.  
  26. number()
  27. {
  28.    if( isdigit( *Lineptr ) )
  29.    {
  30.       push( atoi( Lineptr ) );
  31.       while( isdigit( *Lineptr ) )
  32.          ++Lineptr;
  33.    }
  34. }
  35.  
  36. addition()
  37. {
  38.    int num;
  39.  
  40.    while(1)
  41.    {
  42.       multiplication();
  43.       if( *Lineptr=='+' )
  44.       {
  45.          ++Lineptr;
  46.          multiplication();
  47.          push( pop() + pop() );
  48.       }
  49.       else if ( *Lineptr=='-' )
  50.       {
  51.          ++Lineptr;
  52.          multiplication();
  53.          num = pop();
  54.          push( pop() - num );
  55.       }
  56.       else
  57.          return;
  58.    }
  59. }
  60.  
  61. multiplication()
  62. {
  63.    int num;
  64.  
  65.    while(1)
  66.    {
  67.       number();
  68.       if( *Lineptr=='*' )
  69.       {
  70.          ++Lineptr;
  71.          number();
  72.          push( pop() * pop() );
  73.       }
  74.       else if ( *Lineptr=='/' )
  75.       {
  76.          ++Lineptr;
  77.          number();
  78.          num = pop();
  79.          push( pop() / num );
  80.       }
  81.       else
  82.          return;
  83.    }
  84. }
  85.  
  86. push( n )
  87. {
  88.    if( Stackptr<Stacktop )
  89.       return Stack[ Stackptr++ ] = n;
  90.    puts( "stack overflow\n" );
  91. }
  92.  
  93. pop()
  94. {
  95.    if( Stackptr>0 )
  96.       return Stack[ --Stackptr ];
  97.    puts( "stack underflow\n" );
  98. }
  99.  
  100. isdigit(c){ return '0'<=c && c<='9';}
  101.