1. 程式人生 > >sincerit-杭電oj 1237 簡單計算器

sincerit-杭電oj 1237 簡單計算器

1237 簡單計算器

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 26856 Accepted Submission(s): 9741

Problem Description
讀入一個只包含 +, -, *, / 的非負整數計算表示式,計算該表示式的值。

Input
測試輸入包含若干測試用例,每個測試用例佔一行,每行不超過200個字元,整數和運算子之間用一個空格分隔。沒有非法表示式。當一行中只有0時輸入結束,相應的結果不要輸出。

Output
對每個測試用例輸出1行,即該表示式的值,精確到小數點後2位。

Sample Input
1 + 2
4 + 2 * 5 - 7 / 11
0

Sample Output
3.00
13.36

#include <iostream>
#include <cstring>
#include <iomanip>
#include <stdio.h> 
#include <stack>
using namespace std;
int main() {
  double x;
  char sign;
  while (scanf("%lf", &x)) {
    stack<double
> num; num.push(x); char ch; ch = getchar(); if (x == 0 && ch == '\n') break; // 特殊情況 0 + 1所以要加上ch=='\n'的判斷 scanf("%c", &sign); getchar(); while (scanf("%lf", &x)) { if (sign == '+') { num.push(x); } else if (sign == '-') { num.
push(-x); } else if (sign == '*') { double temp = num.top(); num.pop(); num.push(temp * x); } else if (sign == '/') { double t = num.top(); num.pop(); num.push(t*1.0 / x); } ch = getchar(); // 結束時數字後面有一個換行 if (ch == '\n') break; scanf("%c", &sign); getchar(); } double sum = 0.0; while (num.size()) { sum += num.top(); num.pop(); } //cout << fixed << setprecision(2) << sum << "\n"; printf("%.2f\n", sum); } return 0; }

原先兩個棧模擬的不知道哪裡錯了

#include <iostream>
#include <stdio.h>
#include <stack> 
#include <cstring>
#include <iomanip>
double cal(double x, double y, char ch) {
  if (ch == '+') return y + x;  
  else if (ch == '-') return y - x;
  else if (ch == '*') return y * x;   
  else return y / x;// 入棧再出來的資料剛好相反是y/x 不是x/y 
}
int compare(char a, char b) {
  if (a == '#') return 1;
  else if (b == '*' || b == '/') {
    if (a == '+' || a == '-') return 1;
  }
  return 0;
}
using namespace std;
int main() {
  string str;
  while (getline(cin, str)) {
    if (str == "0") break;
    stack<char> sign;
    sign.push('#');
    stack<double> num;
    int k = 0;
    for (int i = 0; i < str.size(); i++) {
      if (str[i] >= '0' && str[i] <= '9') {
        k = k * 10 + str[i] - '0';
      } else if (str[i] == ' ') {
        //cout << k << "\n";
        num.push(k*1.0);
        k = 0;
      } else {
        if (compare(sign.top(), str[i]) == 1) {
          sign.push(str[i]);
        } else {
          double x = num.top();
          num.pop();
          double y = num.top();
          num.pop();
          num.push(cal(x, y, sign.top()));
          sign.pop();
          sign.push(str[i]);  // 計算完了之後再把當前符號入棧 
        }
        i++;  // 符號後面的空格要跳過去 
      }
    }
    num.push(k*1.0);  // 最後一個數據還在k中 
    while (sign.size() > 1) {
      double a = num.top();
      num.pop();
      double b = num.top();
      num.pop();
      num.push(cal(a, b, sign.top()));
      sign.pop();
    }
    //cout << fixed << setprecision(2) << num.top() << "\n";
    printf("%.2f\n", num.top());
  }
  return 0;
}