#include #include #include "stack5.h" #include "complex2.h" int getop(Stack* s, Complex* n1, Complex* n2) { if (s->empty()) { printf("empty stack!\n"); return 0; } *n2 = s->pop(); if (s->empty()) { s->push(*n2); printf("two operands needed!\n"); return 0; } *n1 = s->pop(); return 1; } int main(void) { Stack* s = new Stack; while (1) { char str[31]; float re, im; printf("> "); gets(str); if (sscanf(str, " %f+%fi", &re, &im)==2) s->push(Complex(re,im)); else if (sscanf(str, " %f", &re)==1) s->push(Complex(re)); else { Complex n1, n2; char c; sscanf(str, "%c", &c); switch(c) { case '+': if (getop(s, &n1, &n2)) s->push(n1+n2); break; case '-': if (getop(s, &n1, &n2)) s->push(n1-n2); break; case '/': if (getop(s, &n1, &n2)) s->push(n1/n2); break; case '*': if (getop(s, &n1, &n2)) s->push(n1*n2); break; case 'q': delete s; return 0; default: printf("error\n"); } } int i = 0; StackIterator si(s); while (!si.end()) { Complex x(si.next()); printf("%d:%6.2f+%.2fi\n", i++, x.re(), x.im()); } } }