c++使用逆波兰式处理简单的数字表达式

关于使用逆波兰式处理简单的数字表达式

表达式类似 ( 2 ∗ 5 + ( 3 + 7 ) ) ∗ 8 (2*5+(3+7))*8 (25+(3+7))8

​ 今天写了一下午,一开始想得是使用二叉树把表达式存起来,但是做了大概四五个小时,搞到半夜两点多,发现代码写起来很复杂,于是没忍住查了一下,百度上写得很明白,使用逆波兰式可以使计算变得很简单,逆波兰式其实也就是二叉树的后序遍历,所以花了点时间,写出了一个将表达式转换成逆波兰式的程序:

上面的字符串经过处理的结果是: 25 ∗ 37 + + 8 ∗ 25*37++8* 2537++8

程序中为了方便处理,在末尾加入了#,后续处理将#号去掉即可。

这个程序有几点问题:只能处理较为简单的四则运算,只能处理0-9的数字,而且无法处理字母,所以下一步要修改程序,解决以上的问题。

MStringExpTree::MStringExpTree(QString str)
{
    QStack<QChar> RPN;
    QStack<QChar> theOperators;
    theOperators.push('#');
    str.push_back('#');

    for(int i=0;i<str.size();i++){
        QChar temp = str.at(i);
        if(isNumber(temp))
            RPN.push(temp);
        if(temp == '(')
            theOperators.push(temp);
        if(temp == ')'){
            while (theOperators.top() !='(') {
                RPN.push(theOperators.pop());
            }
            theOperators.pop();
        }
        if(isOperator(temp)){
            if(higherThan(temp,theOperators.top()))
                theOperators.push(temp);
            else{
                RPN.push(theOperators.pop());
                while (lowerThan(temp,theOperators.top())) {
                    RPN.push(theOperators.pop());
                }
                theOperators.push(temp);
            }
        }
        if(temp == '#'){
            while (!theOperators.isEmpty()) {
                temp = theOperators.pop();
                RPN.push(temp);
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
逆波兰式也称为后缀表达式,是一种不含括号的数学表达式。其计算顺序与中缀表达式相同,但是可以通过栈来实现计算。 下面是用 C++ 实现逆波兰式的生成和计算的示例代码: ```c++ #include <iostream> #include <stack> #include <string> #include <vector> using namespace std; int main() { // 输入逆波兰式 string rpn; cout << "请输入逆波兰式:" << endl; getline(cin, rpn); // 将逆波兰式拆分为操作数和操作符 vector<string> tokens; string token = ""; for (int i = 0; i < rpn.length(); i++) { if (rpn[i] == ' ') { tokens.push_back(token); token = ""; } else { token += rpn[i]; } } tokens.push_back(token); // 计算逆波兰式 stack<int> numStack; for (int i = 0; i < tokens.size(); i++) { string token = tokens[i]; if (token == "+" || token == "-" || token == "*" || token == "/") { int num2 = numStack.top(); numStack.pop(); int num1 = numStack.top(); numStack.pop(); int result; if (token == "+") { result = num1 + num2; } else if (token == "-") { result = num1 - num2; } else if (token == "*") { result = num1 * num2; } else if (token == "/") { result = num1 / num2; } numStack.push(result); } else { int num = stoi(token); numStack.push(num); } } // 输出结果 cout << "计算结果:" << numStack.top() << endl; return 0; } ``` 这个程序首先要求用户输入一个逆波兰式,然后将其拆分为操作数和操作符。接着,程序使用一个栈来计算逆波兰式的值。对于每个操作符,程序将栈顶的两个数弹出,计算后将结果压回栈中。对于每个操作数,程序将其转换为整数并压入栈中。最后,程序输出计算结果。 注意,这个程序没有对输入的逆波兰式进行任何错误检查,如果输入的逆波兰式不符合规范,程序可能会出错。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值