#include <iostream>
#include <string>
#include <stack>
#include <cctype>
#include <stdexcept>
#include <cmath>
#include <iomanip>
#include <cstdlib>  // 用于调用系统命令（system）
#include <algorithm> // 用于查找字符

using namespace std;

// 运算符优先级：数字越大优先级越高
int getPriority(char op) {
    switch (op) {
        case '(': return 0;
        case '+': case '-': return 1;
        case '&': case '|': return 2;  // 位与、位或
        case '<<': case '>>': return 3; // 移位运算
        case '*': case '/': case '%': return 4;
        case '^': return 5;             // 幂运算
        case '√': case '厂': return 6;  // 根号（双符号，优先级相同）
        case '~': return 7;             // 按位取反（单目运算符）
        default: return -1;
    }
}

// 执行双目运算
double calculate(double a, double b, char op) {
    switch (op) {
        case '+': return a + b;
        case '-': return a - b;
        case '*': return a * b;
        case '/': 
            if (fabs(b) < 1e-9) throw runtime_error("除数不能为0");
            return a / b;
        case '%': 
            if (fabs(b) < 1e-9) throw runtime_error("取模除数不能为0");
            return fmod(a, b);  // 浮点数取模
        case '&': return (long long)a & (long long)b;  // 按位与（强转整数）
        case '|': return (long long)a | (long long)b;  // 按位或（强转整数）
        case '<<': return (long long)a << (long long)b; // 左移位
        case '>>': return (long long)a >> (long long)b; // 右移位
        case '^': return pow(a, b);                     // 幂运算（a^b = a的b次方）
        default: throw runtime_error("不支持的运算符: " + string(1, op));
    }
}

// 处理单目运算符：根号（√/厂）、按位取反（~）
double calculateUnary(double num, char op) {
    switch (op) {
        case '√': case '厂':  // 同时处理两个根号符号
            if (num < 0) throw runtime_error("根号下不能为负数");
            return sqrt(num);  // 平方根
        case '~': return ~(long long)num;  // 按位取反（仅整数）
        default: throw runtime_error("不支持的单目运算符: " + string(1, op));
    }
}

// 预处理输入：统一根号符号（将“厂”转为“√”，方便后续处理）
string preprocessInput(const string& input) {
    string processed = "";
    for (char c : input) {
        if (c == '厂') {
            processed += '√';  // 统一转为√，后续逻辑无需重复判断
        } else {
            processed += c;
        }
    }
    return processed;
}

// 检测表达式是否包含特殊运算符：~、厂、√、^、%、&、|
bool hasSpecialOperators(const string& input) {
    const string specialOps = "~厂√^%&|";
    for (char c : input) {
        if (specialOps.find(c) != string::npos) {
            return true;
        }
    }
    return false;
}

// 调用系统计算器（跨平台兼容）
void openSystemCalculator() {
#ifdef _WIN32
    system("calc.exe");  // Windows 系统计算器
#elif __APPLE__
    system("open /System/Applications/Calculator.app");  // macOS 系统计算器
#else
    system("gnome-calculator || kcalc || xcalc");  // Linux 系统计算器（兼容不同桌面环境）
#endif
    cout << "计算结果大于10000，太难了，你去问问专业的吧！\n" << endl;
}

// 调用系统计算器（跨平台兼容）
void openSystemCalculator() {
#ifdef _WIN32
    system("calc.exe");  // Windows 系统计算器
#elif __APPLE__
    system("open /System/Applications/Calculator.app");  // macOS 系统计算器
#else
    system("gnome-calculator || kcalc || xcalc");  // Linux 系统计算器（兼容不同桌面环境）
#endif
    cout << "已为你打开系统计算器！\n" << endl;
}

// 中缀表达式转后缀表达式（逆波兰表示法）
bool infixToPostfix(const string& infix, string& postfix) {
    string processedInfix = preprocessInput(infix); // 预处理输入，统一根号符号
    stack<char> opStack;
    postfix.clear();
    int i = 0;
    int len = processedInfix.length();

    while (i < len) {
        // 跳过空格
        if (isspace(processedInfix[i])) {
            i++;
            continue;
        }

        // 数字（支持整数和小数，如 123 或 123.45）
        if (isdigit(processedInfix[i]) || processedInfix[i] == '.') {
            int dotCount = 0;
            while (i < len && (isdigit(processedInfix[i]) || processedInfix[i] == '.')) {
                if (processedInfix[i] == '.') {
                    dotCount++;
                    if (dotCount > 1) { // 多个小数点
                        cout << "错误：非法小数格式（多个小数点）" << endl;
                        return false;
                    }
                }
                postfix += processedInfix[i];
                i++;
            }
            postfix += ' '; // 用空格分隔数字
        }
        // 左括号
        else if (processedInfix[i] == '(') {
            opStack.push(processedInfix[i]);
            i++;
        }
        // 右括号
        else if (processedInfix[i] == ')') {
            while (!opStack.empty() && opStack.top() != '(') {
                postfix += opStack.top();
                postfix += ' ';
                opStack.pop();
            }
            if (opStack.empty()) { // 括号不匹配
                cout << "错误：括号不匹配（缺少左括号）" << endl;
                return false;
            }
            opStack.pop(); // 弹出左括号
            i++;
        }
        // 根号（√，已统一处理）：单目运算符
        else if (processedInfix[i] == '√') {
            while (!opStack.empty() && getPriority(opStack.top()) > getPriority('√')) {
                postfix += opStack.top();
                postfix += ' ';
                opStack.pop();
            }
            opStack.push('√');
            i++;
        }
        // 按位取反（~）：单目运算符
        else if (processedInfix[i] == '~') {
            while (!opStack.empty() && getPriority(opStack.top()) > getPriority('~')) {
                postfix += opStack.top();
                postfix += ' ';
                opStack.pop();
            }
            opStack.push('~');
            i++;
        }
        // 移位运算符（<< 或 >>）
        else if ((processedInfix[i] == '<' && processedInfix[i+1] == '<') || (processedInfix[i] == '>' && processedInfix[i+1] == '>')) {
            char op1 = processedInfix[i];
            char op2 = processedInfix[i+1];
            while (!opStack.empty() && getPriority(opStack.top()) >= getPriority(op1)) {
                postfix += opStack.top();
                postfix += ' ';
                opStack.pop();
            }
            opStack.push(op1);
            opStack.push(op2);
            i += 2;
        }
        // 其他双目运算符（+、-、*、/、%、&、|、^）
        else {
            char op = processedInfix[i];
            if (getPriority(op) == -1) { // 非法运算符
                cout << "错误：不支持的字符：" << op << endl;
                return false;
            }
            while (!opStack.empty() && getPriority(opStack.top()) >= getPriority(op)) {
                postfix += opStack.top();
                postfix += ' ';
                opStack.pop();
            }
            opStack.push(op);
            i++;
        }
    }

    // 弹出剩余运算符
    while (!opStack.empty()) {
        if (opStack.top() == '(') { // 括号不匹配
            cout << "错误：括号不匹配（缺少右括号）" << endl;
            return false;
        }
        postfix += opStack.top();
        postfix += ' ';
        opStack.pop();
    }

    return true;
}

// 计算后缀表达式
double evaluatePostfix(const string& postfix) {
    stack<double> numStack;
    int i = 0;
    int len = postfix.length();

    while (i < len) {
        if (isspace(postfix[i])) {
            i++;
            continue;
        }

        // 数字（整数或小数）
        if (isdigit(postfix[i]) || postfix[i] == '.') {
            double num = 0.0;
            int dotPos = -1;
            int digitCount = 0;
            while (i < len && (isdigit(postfix[i]) || postfix[i] == '.')) {
                if (postfix[i] == '.') {
                    dotPos = digitCount;
                } else {
                    num = num * 10 + (postfix[i] - '0');
                    digitCount++;
                }
                i++;
            }
            // 处理小数部分
            if (dotPos != -1) {
                num /= pow(10, digitCount - dotPos - 1);
            }
            numStack.push(num);
        }
        // 单目运算符（√、~）
        else if (postfix[i] == '√' || postfix[i] == '~') {
            if (numStack.empty()) throw runtime_error("表达式格式错误（单目运算符后无数字）");
            double num = numStack.top();
            numStack.pop();
            numStack.push(calculateUnary(num, postfix[i]));
            i++;
        }
        // 移位运算符（<< 或 >>）
        else if ((postfix[i] == '<' && postfix[i+1] == '<') || (postfix[i] == '>' && postfix[i+1] == '>')) {
            if (numStack.size() < 2) throw runtime_error("表达式格式错误（移位运算缺少操作数）");
            double b = numStack.top(); numStack.pop();
            double a = numStack.top(); numStack.pop();
            // 移位位数必须是非负整数
            if (b < 0 || fabs(b - round(b)) > 1e-9) {
                throw runtime_error("移位位数必须是非负整数");
            }
            double res;
            if (postfix[i] == '<' && postfix[i+1] == '<') {
                res = (long long)a << (long long)b;
            } else {
                res = (long long)a >> (long long)b;
            }
            numStack.push(res);
            i += 2;
        }
        // 其他双目运算符
        else {
            char op = postfix[i];
            if (numStack.size() < 2) throw runtime_error("表达式格式错误（缺少操作数）");
            double b = numStack.top(); numStack.pop();
            double a = numStack.top(); numStack.pop();
            double res = calculate(a, b, op);
            numStack.push(res);
            i++;
        }
    }

    if (numStack.size() != 1) throw runtime_error("表达式格式错误（操作数/运算符不匹配）");
    return numStack.top();
}

// 主函数：交互逻辑
int main() {
    cout << "===== 多功能计算器 =====" << endl;
    cout << "支持运算符：+ - * / % & | ~ << >> ^ √ 厂" << endl;
    cout << "说明：" << endl;
    cout << "  1. √/厂：根号（如 √16 或 厂16 表示16的平方根）" << endl;
    cout << "  2. ^：幂运算（如 2^3 表示2的3次方）" << endl;
    cout << "  3. &|~<<>>：仅支持整数运算" << endl;
    cout << "  4. 无特殊运算符且结果>10000时，系统会罢工" << endl;
    cout << "  5. 输入 'q' 退出程序" << endl;
    cout << "=========================\n" << endl;

    // 设置输出精度为6位小数
    cout << fixed << setprecision(6);

    string input;
    while (true) {
        cout << "请输入表达式：";
        getline(cin, input);

        // 退出程序
        if (input == "q" || input == "Q") {
            cout << "程序退出..." << endl;
            break;
        }
		
		// 打开系统计算器
		if (input == "c" || input == "C") {
            openSystemCalculator();
            continue;
        }
		 
        // 空输入跳过
        if (input.empty()) continue;

        try {
            string postfix;
            // 中缀转后缀
            if (!infixToPostfix(input, postfix)) {
                continue;
            }
            // 计算后缀表达式
            double result = evaluatePostfix(postfix);
            
            // 核心逻辑：检测特殊运算符 + 结果阈值
            bool hasSpecial = hasSpecialOperators(input);
            if (!hasSpecial && result > 10000) {
                // 无特殊运算符且结果>10000，打开系统计算器，不显示结果
                openSystemCalculator();
            } else {
                // 其他情况正常显示结果
                if (fabs(result - round(result)) < 1e-9) {
                    cout << "计算结果：" << (long long)result << "\n" << endl;
                } else {
                    cout << "计算结果：" << result << "\n" << endl;
                }
            }
        } catch (const exception& e) {
            cout << "错误：" << e.what() << "\n" << endl;
        }
    }

    return 0;
}
