逆波兰式求值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaohaibo_/article/details/83245160

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;
}

猜你喜欢

转载自blog.csdn.net/zhaohaibo_/article/details/83245160
今日推荐