|
hey, im working on a program that uses a stack array to do a simple calculator. The only problem im having is with a bool function in one my STACK class, it should return true if the stack gets down to -1, and false if otherwise, but it ALWAYS returns true. it is accessed from the second if statement in main.
thank you for your help
#include<iostream.h> #include<fstream.h> #include"apstring.h" #include"apvector.h" #include"apstring.cpp"
class STACK { private: int top; double stack[20]; public: STACK(); void push(double x); double pop(); bool isEmpty() { if(top==-1){ return true; }else{ return false; } } double current () { return stack[top+1]; } };
class RPN: public STACK { public: RPN(); void add(); void sub(); void mult(); void div(); };
//RPN Constructor RPN::RPN() { }
void RPN::add() { double first=0, second=0, ans=0; first = pop(); second= pop(); push(first + second); ans=first+second; cout<<"\nResult of addition: " <<ans<<endl<<endl; } void RPN::sub() { double first=0, second=0, ans=0; first = pop(); second= pop(); push(first - second); ans=first-second; cout<<"\nResult of subtraction: " <<ans<<endl<<endl; } void RPN::mult() { double first=0, second=0, ans=0; first = pop(); second= pop(); push(first * second); ans=first*second; cout<<"\nResult of multiplication: " <<ans<<endl<<endl; } void RPN::div() { double first=0, second=0, ans=0; first = pop(); second= pop(); push(first / second); ans=first/second; cout<<"\nResult of division: " <<ans<<endl<<endl; }
//Default Constructor STACK::STACK() { top=-1; for(int i=0;i<20;i++) { stack[i]=0; } }
//Constructor 1 void STACK::push (double x) { top++; stack[top] = x; }
//Constructor 2 double STACK::pop () { double x = stack[top]; top--; return x; }
//Main int main () { int pushnum=0, pushcounter=1; apstring choice; apstring calcchoice; STACK empty; RPN b; do{ cout<<"Enter 'push' or 'pop', and 'q' once you wish to make the calculations: "; cin>>choice; if(choice == "q") { break; } if(choice == "pop") { if(!empty.isEmpty()) { b.pop(); cout<<"\nCurrent number is: "<<b.current()<<endl<<endl; }else{ cout<<"\n\nPop limit reached!"<<endl<<endl; } }
if(choice == "push") {
if(pushcounter<20) { cout<<"\n\nEnter number to push: "; cin>>pushnum; b.push(pushnum); cout<<"\n\nCurrent number is: "<<pushnum<<endl<<endl; }else{ cout<<"\n\nPush limit reached!"<<endl<<endl; } } }while(choice != "q"); //---------------------------------------------------------------------- do{ cout<<"\n\nEnter 'add', 'sub', 'mult', 'div', or 'q' to quit: "; cin>>calcchoice; //Calculator Commands if(calcchoice == "q") { break; } if(calcchoice == "add") { b.add(); } if(calcchoice == "sub") { b.sub(); }
if(calcchoice == "mult") { b.mult(); } if(calcchoice == "div") { b.div(); } }while(choice != "q"); system("PAUSE"); return 1; }
|