H.简单计算器

恶心的模拟题......

#include<bits/stdc++.h>

using namespace std;

int main(){
  ios::sync_with_stdio(false);
  // freopen("in.in", "r", stdin);
  vector<double> nums;
  vector<double> nums2;
  vector<char> op, op2;
  char s[205];
  string temp;
  while(1){
    gets(s);
    temp = s;
    if(temp == "0")
      break;
    op.clear();
    op2.clear();
    nums.clear();
    nums2.clear();
    string store = "";
    for(int i=0; i<temp.length(); i++){
      if(temp[i] == '+' || temp[i] == '-' || temp[i] == '*' || temp[i] == '/'){
        op.push_back(temp[i]);
        if(temp[i] == '+' || temp[i] == '-')
          op2.push_back(temp[i]);
        nums.push_back(stoi(store));
        store = "";
      }else if(temp[i] >= '0' && temp[i] <= '9')
        store += temp[i];
    }
    nums.push_back(stoi(store));

    for(int i=0; i<nums.size(); i++){
      double a = nums[i];
      double b = nums[i+1];
      if(i < op.size() && op[i] == '*'){
        nums[i+1] = a * b;
      }
      else if(i < op.size() && op[i] == '/'){
        nums[i+1] = a / b;
      }
      else
        nums2.push_back(nums[i]);

    }

    // for(auto x : op2)
    //   cout << x << " ";
    // cout << endl;

    double ans = nums2[0];
    for(int i=0; i<op2.size(); i++){
      double b = nums2[i+1];
      if(op2[i] == '+')
        ans += nums2[i+1];

      else if(op2[i] == '-'){
        ans -= nums2[i+1];
      }
      // cout << ans << " " << a << " " << b << endl;
    }

    printf("%.2lf\n", ans);


  }
  return 0;
}

猜你喜欢

转载自www.cnblogs.com/ssNiper/p/11361085.html