C++模板写计算器 带()

来源:互联网 发布:大数据分析平台架构 编辑:程序博客网 时间:2024/05/17 16:54
#include "stack.h"#include <iostream>using namespace std;int main(){Stack<int> number_;Stack<char> operator_;char src[100];cout << "请输入表达式" << endl;cin >> src;int i = 0;while (1){if (src[i] == '\0'){int num1;int num2;while (operator_.Empty() == false){num1 = number_.getTop();number_.Pop();num2 = number_.getTop();number_.Pop();int result = cal(num2, num1, operator_.getTop());operator_.Pop();number_.Push(result);//i不增加}break;}switch (src[i]){case '(':{operator_.Push(src[i]);i++;break;}case ')':{int num1;int num2;int num3;int result;int result_n;if (compare(operator_.getTop()) == 3){num1 = number_.getTop();number_.Pop();num2 = number_.getTop();number_.Pop();result = cal(num2, num1, operator_.getTop());operator_.Pop();if (operator_.getTop() == '('){number_.Push(result);i++;operator_.Pop();break;}else{num3 = number_.getTop();number_.Pop();result_n = cal(num3, result, operator_.getTop());number_.Push(result_n);operator_.Pop();operator_.Pop();i++;break;}}else{num1 = number_.getTop();number_.Pop();num2 = number_.getTop();number_.Pop();result = cal(num2, num1, operator_.getTop());operator_.Pop();number_.Push(result);i++;operator_.Pop();break;}}    case '-':case '+':{if (operator_.Empty() == true){operator_.Push(src[i]);i++;break;}if (compare(src[i]) <= compare(operator_.getTop())){int num1;int num2;num1 = number_.getTop();number_.Pop();num2 = number_.getTop();number_.Pop();int result = cal(num2, num1, operator_.getTop());operator_.Pop();operator_.Push(src[i]);i++;number_.Push(result);}else{operator_.Push(src[i]);i++;}break;}case '*':{operator_.Push(src[i]); i++;break;}case '/':{operator_.Push(src[i]);i++;break;}default: {int num = 0;while (src[i] >= '0' && src[i] <= '9'){num = num * 10 + my_atoi(src[i]);i++;}number_.Push(num);break;}}}cout << number_.getTop() << endl;}
上文为stack.cpp这一部分写的不是很好,应该把主要计算的main里面的计算过程写成函数调用。

#ifndef _STACK_H_#define _STACK_H_template<typename T>class Stack{private:T * s_;int top_;public:Stack();~Stack();void Push(const T& n);void Pop();T& getTop()const;bool Empty()const;};template<typename T>Stack<T>::Stack() :top_(-1){s_ = new T[100];}template<typename T>Stack<T>::~Stack(){delete[]s_;}template<typename T>void Stack<T>::Push(const T & n){if (top_ == 99){throw(1);}top_++;s_[top_] = n;}template<typename T>void Stack<T>::Pop(){if (Empty() == true){throw(1);}top_--;}template<typename T>T & Stack<T>::getTop()const{if (Empty() == true){throw(1);}return s_[top_];}template<typename T>bool Stack<T>::Empty()const{return top_ + 1 == 0;}int compare(char c){if (c == '*' || c == '/'){return 3;}else if (c == '+' || c == '-'){return 2;}else if (c == '('){return 1;}else if (c == '\0'){return 0;}else{return 0;}}int cal(int n, int m, char c){if (c == '+')return n + m;if (c == '-')return n - m;if (c == '*')return n*m;if (c == '/')return n / m;}int my_atoi(char ch){if (ch >= '0' && ch <= '9'){return ch - '0';}}#endif 


这个写的是一个自己的stack模板类。

在vs2015环境下能够编译成功,亲测有效生气

0 0
原创粉丝点击