中缀表达式转后缀表达式,以及计算结果.

//输入的时候加不加空格都行,因为是前缀表达式.
//但是输出中应该要加空格,因为有可能几个数字是挨在一起的情况.


//has not complete the `to_prifix`, because i do not know how to do it.

#include <iostream>
#include <string>
#include <cctype>
#include <stack>
using namespace std;

class Compute{
public:
    Compute(string infix_);
    int Cal();
    string Prefix() { return prefix; }
    string Postfix() { return postfix; }
private:
    string prefix;
    string infix;
    string postfix;
private:
    void to_postfix();
    int cal(int n1, int n2, char c);
    int compare_priory(char x, char y);
};

Compute::Compute(string infix_) : infix(infix_)
{
    to_postfix();
}

int Compute::cal(int n1, int n2, char c)
{
    switch (c){
    case '+': return n1 + n2;
    case '-': return n1 - n2;
    case '*': return n1 * n2;
    case '/': return n1 / n2;
    }
}



int Compute::compare_priory(char x, char y)
{
    if (x == '*' || x == '/') return 1;
       else if ((x == '+' || x == '-') && (y == '+' || y == '-')) return 1;
       else return 0;
}


void Compute::to_postfix()
{
    stack<char> optr;

    int len = infix.length();
    int i;
    for (i = 0; i < len; i++){
        if (infix[i] == ' ') {
            continue;
        } else if (isdigit(infix[i])){
            if (i > 0 && (!isdigit(infix[i-1]))){
                postfix.push_back(' ');
                postfix.push_back(infix[i]);
            }else 
                postfix.push_back(infix[i]);
        } else {
            if (optr.empty() || compare_priory(infix[i], optr.top())){
                optr.push(infix[i]);
            }else {
                while (!optr.empty() && compare_priory(optr.top(), infix[i])){
                    postfix.push_back(' ');
                    postfix.push_back(optr.top());
                    postfix.push_back(' ');
                    optr.pop();
                }
                optr.push(infix[i]);
            }
        }
    }
    while (!optr.empty()){
        postfix.push_back(' ');
        postfix.push_back(optr.top());
        postfix.push_back(' ');
        optr.pop();
    }
    if (postfix.back() == ' ') postfix.pop_back();
}

int Compute::Cal()
{
    int len = postfix.length();
    if (len == 0) return 0;

    stack<int> s;
    int i;
    int nu = 0;
    for (i = 0; i < len; i ++){
        nu = 0;
        if (postfix[i] == ' ')
            continue;
        else if (isdigit(postfix[i])){
            if (i > 0 && isdigit(postfix[i-1]) && !s.empty()){
                nu = s.top();
                nu = nu * 10 + postfix[i] - '0';
                s.pop();
                s.push(nu);
            }else 
                s.push(postfix[i] - '0');
        }else{
            int n1 = s.top(); s.pop();
            int n2 = s.top(); s.pop();
            s.push(cal(n2, n1, postfix[i]));
        }
    }
    return s.top();
}
            


int main()
{
    Compute c("12 * 3 + 24 * 35 / 5 - 46");
    cout << c.Postfix() << endl;
    cout << "the result is " << c.Cal() << endl;
    return 0;
}
posted on 2015-08-13 16:39 ii沙漠 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/shamoof/p/4727729.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您编写一个函数,实现中缀表达式转后缀表达式,并计算最后的结果。以下是一个示例代码: ```python def infix_to_postfix(expression): # 定义运算符的优先级 precedence = {'+': 1, '-': 1, '*': 2, '/': 2} postfix = [] # 存储后缀表达式 stack = [] # 运算符栈 for char in expression: if char.isdigit(): postfix.append(char) elif char in '+-*/': while stack and stack[-1] != '(' and precedence[char] <= precedence.get(stack[-1], 0): postfix.append(stack.pop()) stack.append(char) elif char == '(': stack.append(char) elif char == ')': while stack and stack[-1] != '(': postfix.append(stack.pop()) stack.pop() # 弹出左括号 while stack: postfix.append(stack.pop()) return postfix def evaluate_postfix(postfix): stack = [] for char in postfix: if char.isdigit(): stack.append(int(char)) elif char in '+-*/': num2 = stack.pop() num1 = stack.pop() if char == '+': stack.append(num1 + num2) elif char == '-': stack.append(num1 - num2) elif char == '*': stack.append(num1 * num2) elif char == '/': stack.append(num1 / num2) return stack[0] def calculate(expression): postfix = infix_to_postfix(expression) result = evaluate_postfix(postfix) return result ``` 您可以调用 `calculate` 函数,并将中缀表达式作为参数传入。函数将返回计算结果。例如: ```python expression = "3 + 4 * 2 / ( 1 - 5 )" result = calculate(expression) print(result) # 输出结果为 1.0 ``` 请注意,以上代码只支持单个数字的计算,如果需要支持多位数的计算,需要对输入表达式进行解析和拼接。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值