逆序波兰表达式

逆序波兰表达式
题目链接:https://vjudge.net/problem/OpenJ_Bailian-2694

大体思路:
利用c++超强的stl库,将数据放到栈中操作。

参考代码:

#include <algorithm>
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<stack>

using namespace std;

int main ()
{
    string s,str;
    float temp=0,sum=0;
    stack<float> counts;
    stack<string> variable;
    while(cin>>s)//输入字符到字符栈中
    {
        variable.push(s);
        if(getchar()=='\n')
        {
            break;
        }
    }
    while(!variable.empty())//将字符栈里的元素一个个出栈进行运算
    {
        str=variable.top();//将字符栈中的栈顶元素输出到str
        variable.pop();
        if(str[0]>=46&&str[0]<=57)
        {
            temp=stof(str,0);//将字符化为数据
            counts.push(temp);//将数据入到数据栈中
        }
        else
        {
            //匹配运算符
            if(str[0]=='+')//进行运算
            {
                sum=counts.top();
                counts.pop();
                sum+=counts.top();
                counts.pop();
                counts.push(sum);
            }
            if(str[0]=='-')
            {
                sum=counts.top();
                counts.pop();
                sum-=counts.top();
                counts.pop();
                counts.push(sum);
            }
            if(str[0]=='*')
            {
                sum=counts.top();
                counts.pop();
                sum*=counts.top();
                counts.pop();
                counts.push(sum);
            }
            if(str[0]=='/')
            {
                sum=counts.top();
                counts.pop();
                sum/=counts.top();
                counts.pop();
                counts.push(sum);
            }
            sum=0;//将sum初始化,方便下一次计算
        }
    }
    printf("%f",counts.top());//输出栈顶元素,此时栈顶只有一个元素就是最终结果
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值