题解 | #简单计算器#

简单计算器

https://www.nowcoder.com/practice/5759c29a28cb4361bc3605979d5a6130

说实话,当初学的时候还觉得很简单。
结果自己写,写的就一塌糊涂。ε=(´ο`*)))唉

需要注意的几点:
  1. 数据类型。涉及到“11”这种多位的数字怎么从字符串转换为整数
  2. 出栈的顺序等。这个可以按算法原理自己用实际的例子推导一遍,尤其是最后的处理,也就是$后面的。
  3. 最后就是各种小逻辑(我debug了好久呢)
#include<iostream>
#include<stdio.h>
#include<string>
#include<stack>
#include<vector>
using namespace std;

float calculateFunc(float x, float y, char op){
    float ans = 0;
    if(op == '+')
        ans = y+x;
    else if(op == '-')
        ans = x-y;
    else if(op == '*')
        ans = x*y;
    else
        ans = x*1./y;
    return ans;
}

int str2int(string x){
    int ans = 0;
    for(int i=0;i<x.size();++i){
        ans = ans*10+x[i]-'0';
    }
    return ans;
}

int main(){
    string s;
    vector<string> ss;
    while(cin >> s){
        if(s=="0")
            return 0;
        ss.push_back(s);
        while(cin >> s){
            ss.push_back(s);
            if(cin.get()=='\n') break;
        }
        ss.push_back("$");
        stack<char> sign;
        stack<float> num;
        sign.push('#');
        for(int i=0;i<ss.size() && !sign.empty();++i){
            char c;
            if(isdigit(ss[i][0])){
                num.push(str2int(ss[i]));
                continue;
            }else
                c = ss[i][0];
            if(c == '$'){
                while(sign.top() != '#'){
                    char op = sign.top();
                    float x = num.top();
                    num.pop();
                    float y = num.top();
                    num.pop();
                    num.push(calculateFunc(y, x, op));
                    sign.pop();
                }
                printf("%.2f\n", num.top());
                sign.pop();
                num.pop();
                ss.clear();
                break;
            }
            else{
                char op = sign.top();
                if(op == '#'){
                    sign.push(c);
                }else
                if(op == '+' || op == '-'){
                    if(c=='*' || c=='/'){
                        sign.push(c);
                    }else{
                        float x = num.top();
                        num.pop();
                        float y = num.top();
                        num.pop();
                        num.push(calculateFunc(y, x, op));
                        sign.pop();
                        sign.push(c);
                    }
                }else{
                    float x = num.top();
                    num.pop();
                    float y = num.top();
                    num.pop();
                    num.push(calculateFunc(y, x, op));
                    sign.pop();
                    --i;
                    // sign.push(c);
                }
            }
        }
    }
    return 0;
}


全部评论

相关推荐

04-13 18:10
门头沟学院 Java
dawn___:以后只用老年机
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务