宣本人造的计算器
  • 板块灌水区
  • 楼主luogu140658945
  • 当前回复12
  • 已保存回复12
  • 发布时间2024/12/26 21:19
  • 上次更新2024/12/27 16:26:25
查看原帖
宣本人造的计算器
1112643
luogu140658945楼主2024/12/26 21:19
#include<bits/stdc++.h>
#include<windows.h>
using namespace std;
long long js(double num1, double num2, char f) {
    switch (f) {
        case '+': return num1 + num2;
        case '-': return num1 - num2;
        case '*': return num1 * num2;
        case '/': return num1 / num2;
        case '%': return long long(num1) % long long(num2);
    }
}
bool cmp(char op1, char op2) {
    if (op2 == '(' || op2 == ')') {
        return 0;
    }
    if (op1 == '*' || op1 == '/' || op1 == '%') {
        return 1;
    }
    return 0;
}
double nb(string str) {
    stack<double> s;
    stack<char> f;
    for (int i = 0; i < str.size(); i++) {
        char ch = str[i];
        if (isdigit(ch)) { 
            double num = 0;
            bool b = 0;
            double w = 1;
            while (i < str.size() && (isdigit(str[i]) || str[i] == '.')) {
                w *= b?10:1;
                if (str[i] == '.') {
                    b = 1;
                }
                else {
                    num = num * 10 + (str[i] - '0');
                }
                i++;
            }
            i--;
            s.push(num / w);
        }
        else if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%') { 
            while (!f.empty() && cmp(ch, f.top())) {
                char fh = f.top();
                f.pop();
                double num2 = s.top();
                s.pop();
                double num1 = s.top();
                s.pop();
                s.push(js(num1, num2, fh));
            }
            f.push(ch);
        }
        else if (ch == '(') { 
            f.push(ch);
        }
        else if (ch == ')') { 
            while (f.top() != '(') {
                char op = f.top();
                f.pop();
                double num2 = s.top();
                s.pop();
                double num1 = s.top();
                s.pop();
                s.push(js(num1, num2, op));
            }
            f.pop(); 
        }
    }

    while (!f.empty()) {
        char op = f.top();
        f.pop();
        double num2 = s.top();
        s.pop();
        double num1 = s.top();
        s.pop();
        s.push(js(num1, num2, op));
    }

    return s.top();
}
int main() {
    system("title 简易计算器");
    string str;
    while (1) {
        getline(cin, str);
        cout<< nb(str)<<"\n";
    }
    return 0;
}
2024/12/26 21:19
加载中...