blob: 26a9f84f74699abd0e8714d941ec583071a37907 (
plain) (
tree)
|
|
#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");
}
|