Calculator

下面的两个版本主要是中缀转前后缀表达式的方法不一样:

第一个,利用栈来实现:

// 代码说明:这份代码是计算器的第一个实现方法,使用一个ExpressionTransformation类
// 改自于本人之前所写的关于同类问题的博客,附上地址:http://blog.163.com/night_return_0/blog/static/2331110262014417019153/
// 但是那个时候写博客并没有考虑负数以及double类型的问题,现已完善
// 这个类可以将中缀表达式转化为前缀或后缀表达式,并根据前缀或后缀表达式进行计算,也就是有两套计算方法
// 支持负数、多数位、括号、空格的出现
// 无论是用后缀计算还是用前缀计算都在Sicily上测试通过

#ifndef _EXPRESSION_TRANSFORMATION_H
#define _EXPRESSION_TRANSFORMATION_H

#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
using namespace std;

class ExpressionTransformation {
  public:
    string trans_to_prefix_expression_to_s(string);  // 将得到的表达式转化为前缀表达式
    double calculate_from_prefix_expression();  // 根据前缀表达式计算值
    string trans_to_postfix_expression_to_s(string);  // 将得到的表达式转化为后缀表达式
    double calculate_from_postfix_expression();  // 根据后缀表达式计算值
    bool bracket_check(string);  // 匹配括号

  private:
    vector<string> ans_vector_pre;  // 存放前缀表达式,这样放可以区分超过1位的数字
    string pre_string;  // 存放前缀表达式
    vector<string> ans_vector_post;  // 存放后缀表达式
    string post_string;  // 存放后缀表达式
};

inline int prior(char op) {  // 计算优先级函数
    if (op == '+' || op == '-') {
        return 1;
    } else if (op == '*' || op == '/' || op == '%') {
        return 2;
    } else {
        return 0;
    }
}

double string_to_double(string in) {  // 将输入的字符串转化为相应数字函数
    char s[50];
    for (int i = 0; i < 50; i++) {
        s[i] = '\0';
    }
    for (int i = 0; i < in.size(); i++) {
        s[i] = in[i];
    }
    double ans;
    sscanf(s, "%lf", &ans);
    return ans;
}

string erase_blank(string s) {  // 去除空格函数
    for (int i = 0; i < s.size();) {
        if (s[i] == ' ') s.erase(i, 1);
        else i++;
    }
    return s;
}

bool ExpressionTransformation::bracket_check(string in) {
    stack<char> st_bracket;
    for (int i = 0; i < in.size(); i++) {
        if (in[i] == '(' || in[i] == ')') {
            if (st_bracket.empty()) {
                st_bracket.push(in[i]);
            } else {
                if (st_bracket.top() == '(' && in[i] == ')') {
                    st_bracket.pop();
                } else {
                    st_bracket.push(in[i]);
                }
            }
        }
    }
    if (st_bracket.empty()) {
        return 1;
    } else {
        return 0;
    }
}

string ExpressionTransformation::trans_to_postfix_expression_to_s(string in) {

    stack<char> op;  // 操作符栈
    ans_vector_post.clear();  // 后缀表达式存放数组
    bool nextIsNega = false;  // 判断负数
    for (int i = 0; i < in.size();) {
        char c = in[i];
        if ((i > 0 && (in[i - 1] == '+' || in[i - 1] == '-' || in[i - 1] == '*' || in[i - 1] == '/') && in[i] == '-') || (i == 0 && in[i] == '-')) {
            nextIsNega = true;
            i++;
            continue;
        }
        if ('0' <= c && c <= '9') {  // 是数字直接插入
            string num;
            int j;
            for (j = i; j < in.size() && '0' <= in[j] && in[j] <= '9'; j++) {
                num.push_back(in[j]);
            }
            if (nextIsNega) {
                num = "-" + num;
                nextIsNega = false;
            }
            ans_vector_post.push_back(num);
            i = j;
        } else {
            if (c == '(') {  // 是开括号直接插入
                op.push('(');
            } else {
                if (c == ')') {  // 是闭括号就把原本栈中的运算符都输出,直到遇到开括号,注意开括号要丢弃
                    while (op.top() != '(') {
                        string temp;
                        temp.push_back(op.top());
                        ans_vector_post.push_back(temp);
                        op.pop();
                    }
                    op.pop();
                } else {  // 假如是加减乘除取余
                    if (op.empty()) {  // 操作符栈是空就直接插入
                        op.push(c);
                    } else {  // 如果扫描到的运算符优先级高于栈顶运算符则,把运算符压入栈。否则的话,就依次把栈中运算符弹出加到数组ans的末尾,直到遇到优先级低于扫描到的运算符或栈空,并且把扫描到的运算符压入栈中
                        if (prior(c) > prior(op.top())) {
                            op.push(c);
                        } else {
                            while (!op.empty() && prior(c) <= prior(op.top())) {
                                string temp;
                                temp.push_back(op.top());
                                ans_vector_post.push_back(temp);
                                op.pop();
                            }
                            op.push(c);
                        }
                    }
                }
            }
            i++;
        }
    }
    while (!op.empty()) {  // 注意把操作符栈中的剩余操作符输出
        string temp;
        temp.push_back(op.top());
        ans_vector_post.push_back(temp);
        op.pop();
    }

    post_string.clear();  // 构造string并返回
    for (int i = 0; i < ans_vector_post.size(); i++) {
        post_string += ans_vector_post[i];
    }

    return post_string;
}

double ExpressionTransformation::calculate_from_postfix_expression() {

    //利用栈对后缀表达式求值,直接从后缀表达式的左往右扫描,遇到数字放入栈中,遇到字符就把栈顶的两个数字拿出来算,然后再放进栈

    stack<double> ans_post;
    for (int i = 0; i < ans_vector_post.size(); i++) {
        double x, y;
        if (('0' <= ans_vector_post[i][0] && ans_vector_post[i][0] <= '9') || (ans_vector_post[i][0] == '-' && '0' <= ans_vector_post[i][1] && ans_vector_post[i][1] <= '9')) {
            ans_post.push(string_to_double(ans_vector_post[i]));
        } else {
            y = ans_post.top();  // 注意顺序,这里好比xy+就是x+y
            ans_post.pop();
            x = ans_post.top();
            ans_post.pop();
            if (ans_vector_post[i][0] == '+') {
                ans_post.push(x + y);
            } else if (ans_vector_post[i][0] == '-') {
                ans_post.push(x - y);
            } else if (ans_vector_post[i][0] == '*') {
                ans_post.push(x * y);
            } else if (ans_vector_post[i][0] == '/') {
                ans_post.push(x / y);
            }
        }
    }
    return ans_post.top();
}

string ExpressionTransformation::trans_to_prefix_expression_to_s(string original_in) {

    stack<char> op;
    vector<string> temp_vector_pre;

    string in;
    for (int i = 0; i < original_in.size(); i++) {  // 进行前缀表达式转化的时候实现要对表达式做倒序处理
        in.push_back(original_in[original_in.size() - 1 - i]);
    }
    for (int i = 0; i < in.size();) {  // 但是直接倒序会将表达式中的数字倒过来,比如123到321,所以要还原
        if ('0' <= in[i] && in[i] <= '9') {
            string temp_reverse_part;
            int j;
            for (j = i; j < in.size() && '0' <= in[j] && in[j] <= '9'; j++) {}
            if ((j < in.size() - 1 && in[j] == '-' && (in[j + 1] == '+' || in[j + 1] == '-' || in[j + 1] == '*' || in[j + 1] == '/')) || (j + 1 == in.size() && in[j] == '-')) j++;  // 负数的特殊划定
            for (int k = j - 1; k >= i; k--) {
                temp_reverse_part.push_back(in[k]);
            }
            for (int k = i; k < j; k++) {
                in[k] = temp_reverse_part[k - i];
            }
            i = j;
        } else {
            i++;
        }
    }

    bool nextIsNega = false;
    for (int i = 0; i < in.size();) {
        if ((i > 0 && (in[i - 1] == '+' || in[i - 1] == '-' || in[i - 1] == '*' || in[i - 1] == '/') && in[i] == '-') || (i == 0 && in[i] == '-')) {
            nextIsNega = true;
            i++;
            continue;
        }
        char c = in[i];
        if ('0' <= c && c <= '9') {  // 是数字直接插入
            string num;
            int j;
            for (j = i; j < in.size() && '0' <= in[j] && in[j] <= '9'; j++) {
                num.push_back(in[j]);
            }
            if (nextIsNega) {
                num = "-" + num;
                nextIsNega = false;
            }
            temp_vector_pre.push_back(num);
            i = j;
        } else {
            if (c == ')') {  // 闭括号直接插入
                op.push(c);
            } else {
                if (c == '(') {  // 开括号就将操作符栈中的操作符输出,直到遇上闭括号
                    while (op.top() != ')') {
                        string temp;
                        temp.push_back(op.top());
                        temp_vector_pre.push_back(temp);
                        op.pop();
                    }
                    op.pop();
                } else {
                    if (op.empty()) {  // 操作符是空直接插入
                        op.push(c);
                    } else {
                        if (prior(c) >= prior(op.top())) {  // 这里跟后缀表达式有细微区别
                            op.push(c);
                        } else {
                            while (!op.empty() && prior(c) < prior(op.top())) {  // 同上
                                string temp;
                                temp.push_back(op.top());
                                temp_vector_pre.push_back(temp);
                                op.pop();
                            }
                            op.push(c);
                        }
                    }
                }
            }
            i++;
        }
    }
    while (!op.empty()) {  // 注意操作符栈里还有东西要输出
        string temp;
        temp.push_back(op.top());
        temp_vector_pre.push_back(temp);
        op.pop();
    }

    ans_vector_pre.clear();  // 输出结果还要再倒序
    for (int i = 0; i < temp_vector_pre.size(); i++) {
        ans_vector_pre.push_back(temp_vector_pre[temp_vector_pre.size() - 1 - i]);
    }
    pre_string.clear();  // 转化为string输出
    for (int i = 0; i < ans_vector_pre.size(); i++) {
        pre_string += ans_vector_pre[i];
    }

    return pre_string;
}

double ExpressionTransformation::calculate_from_prefix_expression() {

    //这里的计算类似于后缀表达式,但是要从后往前,并且注意顺序

    stack<double> ans_pre;
    for (int i = ans_vector_pre.size() - 1; i >= 0; i--) {
        double x, y;
        if ('0' <= ans_vector_pre[i][0] && ans_vector_pre[i][0] <= '9' || (ans_vector_pre[i][0] == '-' && ans_vector_pre[i].size() > 1 && '0' <= ans_vector_pre[i][1] && ans_vector_pre[i][1] <= '9')) {
            ans_pre.push(string_to_double(ans_vector_pre[i]));
        } else {
            x = ans_pre.top();  // 这里相当于+xy也就是x+y
            ans_pre.pop();
            y = ans_pre.top();
            ans_pre.pop();
            if (ans_vector_pre[i][0] == '+') {
                ans_pre.push(x + y);
            } else if (ans_vector_pre[i][0] == '-') {
                ans_pre.push(x - y);
            } else if (ans_vector_pre[i][0] == '*') {
                ans_pre.push(x * y);
            } else if (ans_vector_pre[i][0] == '/') {
                ans_pre.push(x / y);
            }
        }
    }
    return ans_pre.top();
}


#endif

int main() {

    std::ios::sync_with_stdio(false);

    int caseNum;

    cin >> caseNum;

    string ss;
    getline(cin, ss);
    cout.setf(ios::fixed);
    cout.precision(3);

    while (caseNum--) {

        cout << endl;

        string s;
        getline(cin, s);

        s = erase_blank(s);

        ExpressionTransformation e;

        string preS = e.trans_to_prefix_expression_to_s(s);
        cout << "Pre Expression : " << preS << endl;
        string postS = e.trans_to_postfix_expression_to_s(s);
        cout << "Post Expression : " << postS << endl;


        cout << "Pre calculate result : " << e.calculate_from_postfix_expression() << endl;  // 利用后缀计算,已在Sicily上运行通过
        cout << "Post calculate result : " << e.calculate_from_prefix_expression() << endl;  // 利用前缀计算,已在Sicily上运行通过

    }

    return 0;
}

第一种方法实现结果:
Calculator - Night -  
第二个通过建树实现:

//代码说明:这份代码是计算机的第二种实现,这里并没有像第一个方式用类处理
//利用由中缀表达式构建数,再由先序后序遍历即可轻松获得前缀后缀表达式
//得到前缀后缀表达式之后的计算和第一种实现方法类似
//支持括号、负数、多位数、空格
//本代码中建树并由树建立前缀后缀表达式计算结果都已在Sicily上运行通过

#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <stdio.h>

using namespace std;

#define NODES 10000  // 树的最大节点数

int l[NODES], r[NODES];  // 左节点和右节点,节点i的左节点右节点分别是l[i]和r[i]
string op[NODES];  // 节点上的值,可能是符号或数字
int counter;  // 节点数

vector<string> postData;  // 用于存放后序遍历得到的数据
string postS;  // 后缀表达式
vector<string> preData;  // 用于存放前序遍历得到的数据
string preS;  // 前缀表达式

bool allNum(string s) {  // 判断字符串是否都是数字组成
    for (int i = 0; i < s.size(); i++) {
        if (!('0' <= s[i] && s[i] <= '9')) return false;
    }
    return true;
}

bool isNum(string s) {  // 判断字符串是否表示一个数字
    return  allNum(s) || (s[0] == '-' && allNum(s.substr(1, s.size() - 1)));
}

string erase_blank(string s) {  // 去除空格函数
    for (int i = 0; i < s.size();) {
        if (s[i] == ' ') s.erase(i, 1);
        else i++;
    }
    return s;
}

double string_to_double(string in) {  // 将输入的字符串转化为相应数字函数
    char s[50];
    for (int i = 0; i < 50; i++) {
        s[i] = '\0';
    }
    for (int i = 0; i < in.size(); i++) {
        s[i] = in[i];
    }
    double ans;
    sscanf(s, "%lf", &ans);
    return ans;
}

int buildTree(string & s, int x, int y) {  // 构建一棵树

    int c1 = -1, c2 = -1, p = 0, u;  // c1、c2分别记录出现在括号外的最右边的加减号和乘除号,p记录括号匹配情况

    if (y - x == 1 || isNum(s.substr(x, y - x))) {  // 如果当前的表达式表示一个数字,以此为树(叶子)
        u = counter++;
         l[u] = r[u] = -1;
         op[u] = s.substr(x, y - x);
        return u;

    }

    for (int i = x; i < y; i++) {

        if (s[i] == '(') {
            p++;
        } else if (s[i] == ')') {
            p--;
        } else if (s[i] == '+' || (s[i] == '-' && i > 0 && s[i - 1] != '+' && s[i - 1] != '-' && s[i - 1] != '*' && s[i - 1] != '/')) {  // 如果是加减号,注意这里要确保是减号而不是负号
            if (p == 0) c1 = i;
        } else if (s[i] == '*' || s[i] == '/') {
            if (p == 0) c2 = i;
        }

    }

    if (c1 < 0) c1 = c2;  //括号外没有+或-,则选括号外的*或/
    if (c1 < 0) return buildTree(s, x + 1, y - 1);  //括号外也没有*或/, 说明表达式被一个括号括住,去括号

    u = counter++;
    l[u] = buildTree(s, x, c1);  // 分支建树,递归进行
    r[u] = buildTree(s, c1+1, y);
    op[u] = s.substr(c1, 1);
    
    return u;

}

void pre_travel(int now) {  // 树的前序遍历

    preData.push_back(op[now]);  // 先读入当前节点
    preS += op[now];

    if (l[now] != -1) pre_travel(l[now]);
    if (r[now] != -1) pre_travel(r[now]);

}

void post_travel(int now) {  // 树的后序遍历

    if (l[now] != -1) post_travel(l[now]);
    if (r[now] != -1) post_travel(r[now]);

    postData.push_back(op[now]);  // 最后才读入当前节点
    postS += op[now];

}

double calculate_from_preS() {  // 从前缀表达式中计算结果
    
    stack<double> ans_pre;
    for (int i = preData.size() - 1; i >= 0; i--) {
        double x, y;
        if ('0' <= preData[i][0] && preData[i][0] <= '9' || (preData[i][0] == '-' && preData[i].size() > 1 && '0' <= preData[i][1] && preData[i][1] <= '9')) {
            ans_pre.push(string_to_double(preData[i]));
        } else {
            x = ans_pre.top();  // 这里相当于+xy也就是x+y
            ans_pre.pop();
            y = ans_pre.top();
            ans_pre.pop();
            if (preData[i][0] == '+') {
                ans_pre.push(x + y);
            } else if (preData[i][0] == '-') {
                ans_pre.push(x - y);
            } else if (preData[i][0] == '*') {
                ans_pre.push(x * y);
            } else if (preData[i][0] == '/') {
                ans_pre.push(x / y);
            }
        }
    }
    return ans_pre.top();

}

double calculate_from_postS() {  // 从后缀表达式计算结果
    
    stack<double> ans_post;
    for (int i = 0; i < postData.size(); i++) {
        double x, y;
        if (('0' <= postData[i][0] && postData[i][0] <= '9') || (postData[i][0] == '-' && '0' <= postData[i][1] && postData[i][1] <= '9')) {
            ans_post.push(string_to_double(postData[i]));
        } else {
            y = ans_post.top();  // 注意顺序,这里好比xy+就是x+y
            ans_post.pop();
            x = ans_post.top();
            ans_post.pop();
            if (postData[i][0] == '+') {
                ans_post.push(x + y);
            } else if (postData[i][0] == '-') {
                ans_post.push(x - y);
            } else if (postData[i][0] == '*') {
                ans_post.push(x * y);
            } else if (postData[i][0] == '/') {
                ans_post.push(x / y);
            }
        }
    }
    return ans_post.top();
}

int main() {

    std::ios::sync_with_stdio(false);

    int caseNum;

    cin >> caseNum;

    string ss;
    getline(cin, ss);

    cout.setf(ios::fixed);
    cout.precision(3);

    while (caseNum--) {

        cout << endl;

        counter = 0;

        string s;

        getline(cin, s);

        s = erase_blank(s);

        buildTree(s, 0, s.size());  // 第一步建树

        preData.clear();
        postData.clear();
        preS.clear();
        postS.clear();

        pre_travel(0);  // 第二步遍历
        post_travel(0);

        cout << "Pre Expression : " << preS << endl;
        cout << "Post Expression : " << postS << endl;

        cout << "Calculate from pre : " << calculate_from_preS() << endl;  // 第三步计算
        cout << "Calculate from post : " << calculate_from_postS() << endl;

    }

    return 0;
}

第二种方法实现结果:

Calculator - Night -  





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值