堆栈-直接-计算中缀算式表达式

程序要求:

输入一个类似2 + 3 * ( 4 + 5 ) – 6/ 4的数学表达式,前提是输入的表达式是正确的,然后计算输出结果(本程序没考虑括号的匹配问题以及除数为0产生的异常

#include <iostream>

#include <cstring>

#include <cctype>

#include <stack>


using namespace std;


void evaluate(stack<int>& numbers,stack<char>& operations);
int input(istream& ins);


int main()
{
    cout<<"Input"<<endl;
    int result=0;
    result=input(cin);
    cout<<result<<endl;
    cout<<"End"<<endl;
    return 0;
}
int input(istream& ins){


    stack<int> numbers;
    stack<char> operations;
    int number;
    char symbol;


    while(ins && ins.peek()!='\n')
    {
        if(isdigit(ins.peek()))
        {
            ins>>number;
            numbers.push(number);
        }
        else if(strchr("*/(",ins.peek())!=NULL)
        {
            ins>>symbol;
            operations.push(symbol);
        }
        else if(ins.peek()==')')
        {
            ins.ignore();
            while(operations.top()!='('){
                evaluate(numbers,operations);
            }
            operations.pop();
        }
        else if(strchr("+-",ins.peek())!=NULL)
        {
            while(!operations.empty() && operations.top()!='(')
            {
                evaluate(numbers,operations);
            }
            ins>>symbol;
            operations.push(symbol);
        }
    }
    while(!operations.empty()){
        evaluate(numbers,operations);
    }
    return numbers.top();
}
void evaluate(stack<int>& numbers,stack<char>& operations){
    int operand1,operand2;
    operand2=numbers.top();
    numbers.pop();
    operand1=numbers.top();
    numbers.pop();
    switch(operations.top())
    {
        case '+':
            numbers.push(operand1+operand2);
            break;
        case '-':
            numbers.push(operand1-operand2);
            break;
        case '*':
            numbers.push(operand1*operand2);
            break;
        case '/':
            numbers.push(operand1/operand2);
            break;
    }
    operations.pop();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值