计算器

· · 个人记录

#include<bits/stdc++.h>
using namespace std;
stack<double>a;
stack<char>b;
char c[10000], s[10000];
int ss, cc;
double  t1 = 0.0, t2 = 0.0;
bool pd1() {
    if ((!b.empty()) && (b.top() == '+' || b.top() == '-' || b.top() == '*' || b.top() == '/')) return 1;
    else return 0;
}
bool pd2() {
    if ((!b.empty()) && (b.top() == '*' || b.top() == '/')) return 1;
    else return 0;
}
void zq() {
    t2 = a.top();
    a.pop();
    t1 = a.top();
    a.pop();
}
void sj() {
    c[cc] = b.top();
    cc++;
    b.pop();
}
void jf(int x) {
    if (pd1() == 1) while (pd1() == 1) sj();
    if (x == 1) b.push('+');
    else b.push('-');
    ss++;
}
void cf(int x) {
    if (pd2() == 1) while (pd2() == 1) sj();
    if (x == 1) b.push('*');
    else b.push('/');
    ss++;
}
void zh() {
    int t = strlen(s);
    while (ss < t) {
        if ('0' <= s[ss] && '9' >= s[ss] || s[ss] == '.') {
            while ('0' <= s[ss] && '9' >= s[ss] || s[ss] == '.') {
                c[cc] = s[ss];
                cc++;
                ss++;
            }
            c[cc] = '@';
            cc++;
        } else if (s[ss] == '+') jf(1);
        else if (s[ss] == '-') jf(2);
        else if (s[ss] == '*') cf(1);
        else if (s[ss] == '/') cf(2);
        else if (s[ss] == '(') {
            b.push('(');
            ss++;
        } else if (s[ss] == ')') {
            while (b.top() != '(') sj();
            b.pop();
            ss++;
        }
    }
    while (!b.empty()) sj();
}
void js() {
    int t = 0, f = 0, tmp = 0;
    double num1 = 0.0, num2 = 0.0;
    while (t < cc) {
        if ('0' <= c[t] && '9' >= c[t]) {
            num1 = 0.0;
            num2 = 0.0;
            f = 0;
            tmp = 0;
            while (c[t] != '@') {
                if (f == 1) {
                    num2 *= 10;
                    num2 += c[t] - '0';
                    tmp++;
                }
                if (c[t] == '.') f = 1;
                if (f == 0) {
                    num1 *= 10;
                    num1 += c[t] - '0';
                }
                t++;
            }
            a.push(num1 + num2 / pow(10, tmp));
        }
        if (c[t] == '@')t++;
        if (c[t] == '+') {
            zq();
            a.push(t1 + t2);
            t++;
        }
        if (c[t] == '-') {
            zq();
            a.push(t1 - t2);
            t++;
        }
        if (c[t] == '*') {
            zq();
            a.push(t1 * t2);
            t++;
        }
        if (c[t] == '/') {
            zq();
            a.push(t1 / t2);
            t++;
        }
    }
}
int main() {
    char t = '@';
    printf("计算器\n");
    while (t == '@') {
        printf("请输入\n");
        cin >> s;
        while (!a.empty()) a.pop();
        while (!b.empty()) b.pop();
        ss = 0;
        cc = 0;
        zh();
        js();
        printf("%.10lf\n按@键继续,其他键跳出\n", a.top());
        cin >> t;
    }
    return 0;
}