Input: suffix expression (with floating-point number)
Output: Calculation result of double type
Code:
#include <stdio.h> #include <stdlib.h> #include <malloc.h> #define ELEMTYPE double#define Stack_init_ Size 100#define increase_size 10#define maxbuffer 10typedef struct sqstack{elemtype *top; Elemtype *base; int initsize;} sqstack;typedef struct sqstack *linkstack;//initialize void Initstack (Sqstack *s) {s->base = (linkstack) malloc (stack_init_ Size * sizeof (elemtype)); if (!s->base) {printf ("Storage space allocation failed ... \ n "); Return } s->top = s->base; S->initsize = stack_init_size;} Enter stack void Push (Sqstack *s,elemtype e) {if (s->top-s->base >= s->initsize-1) {s->base = (Lin Kstack) ReAlloc (S->base, (s->initsize + increase_size) * sizeof (elemtype)); The first s->base is the address of the added storage block, the second is the block address of the storage space before the space is increased, followed by the size of the increased storage block if (!s->base) {printf ("Increase storage space loss Defeat ... \ n "); Return } s->initsize = Increase_size + stack_init_size; } * (s->top) = e; (S->top) + +;} Out stack void Pop (Sqstack *s,elemtype *e) {if (s->top = = s->base) {printf ("stack empty, unable to stack operation ... \ n "); Return } s->top--; *e = *s->top;} Calculate the length of the stack int stacklen (Sqstack s) {return (s.top-s.base);} Inverse Polish Calculator: input inverse polish (suffix expression) output int main () {int i = 0,j,len; Double m,n,t; char c; struct Sqstack s; Char Str[maxbuffer]; Initstack (&s); printf ("Enter the suffix expression you want to evaluate, press the ENTER key to end (two different characters separated by a space): \ n"); scanf ("%c", &c); while (c = ' \ n ') {while ((c >= ' 0 ' &&c <= ' 9 ') | | c = = '. ') {Str[i] = C; i++; Str[i] = ' + '; if (i >=) {printf ("\ n the number entered is too large to cause an error!!! \ n "); return-1; } scanf ("%c", &c); if (c = = ") {t = atof (str);//printf (" \nt is%f\n ", t); Push (&s,t); i = 0; for (j = 0;j < maxbuffer;j++) {Str[j] = ' + '; } break; }} switch (c) {case ' + ': Pop (&s,&m); Pop (&s,&n); Push (&S,N+M); Break Case '-': Pop (&s,&m); Pop (&s,&n); Push (&S,N-M); Break Case ' * ': Pop (&s,&m); Pop (&s,&n); Push (&S,N*M); Break Case '/': Pop (&s,&m); Pop (&s,&n); if (M = = 0) {printf ("\ n divisor is 0, Error!!!") \ n "); return-1; } else {Push (&s,n/m); Break }} scanf ("%c", &c); } Pop (&s,&t); printf ("\ nthe final result is:%f \ n", t); return 0;}
Calculation of inverse Polish (suffix expression)