用栈实现计算器。想不出来错在哪里?最后运行不出来结果。
程序代码:
class stack //栈类 { public: stack(); ~stack(); void clearstack(); //清空 int isempty(); //判空 int length(); //求长度 char gettop(); //取栈顶元素 int push(char); //进栈 int pop(char*); //出栈 int traverse(); //遍历 protected: char *base; //栈底指针 char *top; //栈顶指针 };上面是stack.h
程序代码:
#include <iostream> #include "stack.h" using namespace std; stack::stack() { top=base=new char [10]; } stack:: ~stack() { delete [] base; } void stack::clearstack() //清空 { top=base; } int stack::isempty() //判空 { if(top==base) return 1; else return 0; } int stack::length() //求长度 { return top-base; } char stack::gettop() //取栈顶元素 { if(top==base) return '\0'; else return *(top-1); } int stack::push(char c) //进栈 { if(top-base==9) return 0; else { *top=c; top++; return 1; } } int stack::pop(char* c) //出栈 { if(top==base) return 0; else { c=top; top--; return 1; } } int stack::traverse() //遍历 { if(top==base) return 0; else { for(char *p=top-1;p>top-1;p--) { cout<<*p<<"->"; } cout<<*p<<endl; return 1; } }
上面是stack.cpp
程序代码:
#include <iostream> #include "stack.cpp" #include <cstring> #include <cstdlib> #define N 20 using namespace std; int priority(char c) { if(c=='+'||c=='-') return 2; else if(c=='*'||c=='/') return 3; else return 0; } int count(float a,char ope,float b) { float sum; if(ope=='+') sum=a+b; else if(ope=='-') sum=a-b; else if(ope=='*') sum=a*b; else sum=a/b; return sum; } int main() { char line[N]; float x,y,result; char e; int len,i; stack save1,save2; for(i=0;i<=N;i++) cin>>line[i]; len=strlen(line); for(i=0;i<=len-1;i++) { if(isdigit(line[i])) { save1.push(line[i]); } else { if(priority(line[i])>priority(save2.gettop())) save2.push(line[i]); else { x=save1.gettop(); y=save1.gettop(); e=save2.gettop(); result=count(y,e,x); } } } cout<<result<<endl; return 1; }可能就错在这最后一个?