aboutsummaryrefslogtreecommitdiff
path: root/5.10.c
blob: 26a9f84f74699abd0e8714d941ec583071a37907 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>

#define MAXOP 1000
#define NUMBER_SIG '0'

double ops[MAXOP];
int opsl = 0;      /* ops location */

char getop(char str[]);
double pop(void);
void push(double num);

int 
main(int argc, char *argv[])
{
  int opnum;
  double op2;
  char input;

  for (opnum = 1; --argc; opnum++)
    switch ((input = getop(argv[opnum]))) {
      case NUMBER_SIG :
        push(atof(argv[opnum]));
        break;
      case '*' :
        push(pop() * pop());
        break;
      case '+' :
        push(pop() + pop());
        break;
      case '-' :
        op2 = pop();
        push(pop() - op2);
        break;
      case '/' :
        if ((op2 = pop()) == 0.0)
          printf("Err: deviser cant be zero\n");
        else 
          push(pop() / op2);
        break;
      case '%' :
        op2 = pop();
        if (op2 != 0)
          push(fmod(pop(), op2));
        else 
          printf("Err: deviser cant be zero\n");
        break;
      default :
        printf("Err: unknown command %d-'%c'\n", input, input);
        break;
    }

  printf("Result: %.8g\n", pop());

  return 0;
}

char 
getop(char str[])
{
  /* skip blanks */
  while (isblank(*str))
    str++;

  /* return operators */
  if (!isdigit(*str) && *str != '.' && !isdigit(*(str+1)))
    return *str;

  /* collect numbers */
  else if (isdigit(*str) || *str == '.')
    return NUMBER_SIG;

  return -1;
}

double 
pop(void)
{
  return (opsl > 0) ? ops[--opsl] : 0 ;
}

void
push(double num)
{
  if (opsl <= MAXOP) 
    ops[opsl++] = num;
  else 
    printf("Err: stack full\n");
}