c++实现表达式计算问题

来源:互联网 发布:如何才能成为程序员 编辑:程序博客网 时间:2024/06/18 04:40
#include <iostream>#include <Windows.h>#include <string>using namespace std;//栈的定义template<class T>struct Node{T data;Node *next;};template<class T>class LinkStack{public:LinkStack();~LinkStack();T & GetTop();//获取栈顶元素bool Empty();//判断栈是否为空void Push(T);T Pop();void Clear();const int Length();private:Node<T> *head;int length;};template<class T>LinkStack<T>::LinkStack(){length = 0;head = NULL;}template<class T>void LinkStack<T>::Push(T data){Node<T> *p = new Node<T>p->data = data;p->next = head;head = p;length ++;}template<class T>T & LinkStack<T>::GetTop(){if(length < 0){cout << "栈为空" << endl;exit(0);}return head->data;}template<class T>bool LinkStack<T>::Empty(){if (length == 0)return true;elsereturn false;}template<class T>T LinkStack<T>::Pop(){if (length < 0){cout << "栈为空" << endl;exit(0);}T e = head->data;head = head->next;length --;return e;}template<class T>void LinkStack<T>::Clear(){Node<T> *p = head;while(p != NULL){p = p->next;delete head;head = p;}head = NULL;length = 0;}template<class T>const int LinkStack<T>::Length(){return length;}template<class T>LinkStack<T>::~LinkStack(){Clear();//cout << "析构" << endl;}//栈外优先级const int isw(const char &e){int i = 0;switch(e){case '+':case '-':i = 2;break;case '*':case '/':i = 3;break;case '(':i = 5;break;case '#':i = 0;break;}return i;}//栈内优先级const int isn(const char &e){int i = 0;switch(e){case '+':case '-':i = 2;break;case '*':case '/':i = 3;break;case '(':i = 0;break;case '#':i = 0;break;}return i;}LinkStack<double> figure;//存放数字void Calcalate(const char &oper){double num1 = 0,num2 = 0;num1 = figure.Pop();num2 = figure.Pop();switch(oper){case '+':figure.Push( num1+num2 );break;case '-':figure.Push( num2 - num1 );break;case '*':figure.Push( num1 * num2 );break;case '/':if (num1 != 0){figure.Push( num2/num1 );}else{cout << "出错,除数不能为 0 !" << endl;exit(-1);}break;}}void ReadData(){LinkStack<char> mark;mark.Push('#');char c, getMark;string digit_str = "";cout << "请输入表达式,以输入 # 结束" << endl;cin >> c;while(c != '#'){getMark = mark.GetTop();while ((c >= '0' && c <= '9') || c == '.'){digit_str += c;cin >> c;if ((c < '0' || c > '9') && c != '.'){figure.Push( atof( digit_str.c_str() ) );//把字符数字转变成double型数字,后放入figure栈中digit_str = "";}}if (c == '#'){break;}else if (c == ')'){while(getMark != '('){Calcalate( mark.Pop() );//调用Calcalate函数,进行计算getMark = mark.GetTop();}mark.Pop();//把左括号( 扔出栈}else{while (isn(getMark) >= isw(c)){Calcalate( mark.Pop() );getMark = mark.GetTop();}mark.Push(c);}cin >> c;}while( mark.Length() > 1)//排除#号,所以循环次数要大于1{Calcalate( mark.Pop() );}}int main(){ReadData();cout << "result = " << figure.Pop() << endl;return 0;}