aboutsummaryrefslogtreecommitdiff
path: root/4.11.c
blob: 32bac92af4cd64792f273027ff14a9ff4c07a805 (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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>

#define MAXOP 100
#define NUMBER_SIG '0'

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

int 
main(void)
{
  char str[MAXOP];
  char type;
  double op2;

  while ((type = getop(str)) != EOF) {
    switch (type) {
      case NUMBER_SIG :
        push(atof(str));
        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;
      case '\n' :
        printf("%.8g\n", pop());
        break;
      default :
        printf("Err: unknown command\n");
    }
  }

  return 0;
}

#define MAXVAL 100
double val[MAXVAL];
int sp = 0;

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

void
push(double f)
{
  if (sp < MAXVAL)
    val[sp++] = f;
  else
    printf("Err: stack is full\n");
}


char 
getop(char str[])
{
  static char buff = ' ';
  char input;
  int i;

  /* ignore blanks */
  for (input = buff, str[0] = buff; isblank(input);)
    input = str[0] = getchar();
  
  buff = ' ';

  /* return operator */
  if (!isdigit(input) && input != '.')
    return input;

  /* collect digits*/
  for (i = 1; i < MAXOP && (isdigit(input=getchar()) || input == '.'); i++)
    str[i] = input;

  str[i] = '\0';

  if (input != EOF)
    buff = input;

  return NUMBER_SIG;
}