题解 | 简单计算器

#include<iostream>
#include<stack>

using namespace std;

int main() {
    string s;
    getline(cin, s);

    stack<char> z;//保存运算符
    stack<double> t;//保存数字
    string temp;
    for (int i = 0; i < s.size(); i++) {
        if (s[i] == ' ')continue;
        if (s[i] >= '0' && s[i] <= '9') { //大于个位数
            temp += s[i];
            while (i < s.size()) {
                if (s[i + 1] >= '0' && s[i + 1] <= '9') {
                    temp += s[i + 1];
                    i++;
                } else break;
            }
            int x = atoi(temp.c_str());//字符串转int!!
            double y = (double)x;
            t.push(y);
            temp.clear();
        } else { //保留运算符
            if (z.empty()) {
                z.push(s[i]);
                continue;
            }
            while (z.top() == '*' || z.top() == '/') {
                double x = t.top();
                t.pop();
                double y = t.top();
                t.pop();
                if (z.top() == '*') {
                    x = x * y;
                    t.push(x);
                } else {
                    x = y / x;
                    t.push(x);
                }
                z.pop();
                if (z.empty())break;
            }
            if ((s[i] == '-' || s[i] == '+') && !z.empty()) {
                while (z.top() == '+' || z.top() == '-') {
                    double x = t.top();
                    t.pop();
                    double y = t.top();
                    t.pop();
                    if (z.top() == '+') {
                        x = x + y;
                        t.push(x);
                    } else {
                        x = y - x;
                        t.push(x);
                    }
                    z.pop();
                    if (z.empty())break;
                }
            }
            z.push(s[i]);
        }
    }
    while (!z.empty()) {
        double x = t.top();
        t.pop();
        double y = t.top();
        t.pop();
        if (z.top() == '*') {
            x = x * y;
            t.push(x);
        } else if (z.top() == '/') {
            x = y / x;
            t.push(x);
        } else if (z.top() == '+') {
            x = x + y;
            t.push(x);
        } else if (z.top() == '-') {
            x = y - x;
            t.push(x);
        }
        z.pop();
    }
    printf("%.2f\n", t.top());


}

全部评论

相关推荐

06-02 15:17
门头沟学院 Java
心爱的idea:怎么会呢 应该是打招呼有问题 问就说实习6个月全国可飞随时到岗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务