diff options
author | sinanmohd <pcmsinan@gmail.com> | 2022-06-13 17:25:52 +0530 |
---|---|---|
committer | sinanmohd <pcmsinan@gmail.com> | 2022-06-13 17:25:52 +0530 |
commit | f77b310c590e0443720b4b0cc20e5e40f0365bb7 (patch) | |
tree | 38cf1b088c8b5f7f1025c37c81d0b2952b07413e | |
parent | f766b7a638bd7a9f1172425da4b3ccd4deed1f2f (diff) |
add 4.10
-rw-r--r-- | 4.10.c | 124 |
1 files changed, 124 insertions, 0 deletions
@@ -0,0 +1,124 @@ +#include <stdio.h> +#include <stdlib.h> +#include <ctype.h> +#include <math.h> + +#define MAXLEN 1000 +#define MAXOP 100 +#define NUMBER_SIG '0' + +unsigned sneed_getline(char str[], unsigned len); +double pop(void); +void push(double input); +char getop(char str[], char op[], unsigned *spos); + +int +main(void) +{ + char str[MAXLEN]; + unsigned len, spos; + char op[MAXOP]; + double op2; + + while ((len = sneed_getline(str, MAXLEN)) > 1) { + spos = 0; + while (spos < len) { + switch (getop(str, op, &spos)) { + case '0' : + push(atof(op)); + break; + case '+' : + push(pop() + pop()); + break; + case '*' : + push(pop() * pop()); + break; + case '-' : + op2 = pop(); + printf("hey: %g\n", op2); + 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: unknow command\n"); + } + } + + printf("%.8g\n", pop()); + } + + return 0; +} + +unsigned +sneed_getline(char str[], unsigned len) +{ + char input; + unsigned i; + + for(i = 0; i < len+1 && (input = getchar()) != EOF && input != '\n'; i++) + str[i] = input; + + str[i] = '\0'; + + return i; +} + +#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 input) +{ + if (sp < MAXVAL) + val[sp++] = input; + else + printf("Err: stack full\n"); +} + +char +getop(char str[], char op[], unsigned *spos) +{ + int j; + + /* skip blanks */ + for (; isblank(str[*spos]); (*spos)++) + ; + + /* return operator */ + if (!isdigit(str[*spos]) && str[*spos] != '.') { + return str[(*spos)++]; + } + + /* collect digit s*/ + for (j = 0; j < MAXOP+1 && (isdigit(str[*spos]) || str[*spos] == '.'); j++, (*spos)++) + op[j] = str[*spos]; + + op[*spos] = '\0'; + + return NUMBER_SIG; +} |