逆波兰式求值

mbp送去维修的第一天,想他。
今天又水了道题,get到了istringstream的强大。

题目描述

输入一个逆波兰式 ,计算出它的值。保证数据合法,不会出现除0的情况,输入的数字都是整数

输入

一个逆波兰式

输出

计算结果保留2位小数

样例输入
1 2 + 3 4 + *
样例输出
21.00
#include <bits/stdc++.h>
using namespace std;
int main() {
  stack<double> S;
  string x;
  while (cin >> x) {
    istringstream iss(x);
    double r;
    if (iss >> r) {
      S.push(r);
    } else {
      double second = S.top();
      S.pop();
      double first = S.top();
      S.pop();
      double res = first;
      if (x[0] == '+') {
        res += second;
      } else if (x[0] == '-') {
        res -= second;
      } else if (x[0] == '*') {
        res *= second;
      } else {
        res /= second;
      }
      S.push(res);
    }
  }
  cout << fixed << setprecision(2) << S.top() << endl;
}

Tips:如何判断一个数是否为double

bool number(string tok){
    double d;
    istringstream iss(tok);
    if(iss>>d) return true;
    else return false;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值