题解 | #简单计算器#

简单计算器

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

//高优先级压栈,低或相等优先级弹栈计算即可
#include "stdio.h"
#include "string"
#include "stack"
#include "map"
using namespace std;
stack<char> operStack;
stack<double> numStack;
string str;

void calculate(){
    char operation = operStack.top();operStack.pop();
    double a = numStack.top();numStack.pop();
    double b = numStack.top();numStack.pop();
    double num;
    switch (operation) {
        case '+':
            num=a+b;
            numStack.push(num);break;
        case '-':
            num=b-a;
            numStack.push(num);break;
        case '*':
            num=a*b;
            numStack.push(num);break;
        case '/':
            num=b/a;
            numStack.push(num);break;
        default:
            break;
    }
}

int main(){
    char buf[300];
    map<char,int> priority = {
            {'$',0},
            {'+',1},{'-',1},
            {'*',2},{'/',2}
    };
    while (fgets(buf,300,stdin)!=NULL){
        str=buf;
        str.pop_back();
        if(str=="0")
            break;
        str.push_back('$');
        string num;
        for (int i = 0; i < str.size(); ++i) {
            if(str[i]>='0' && str[i]<='9'){ //是数字
                num.push_back(str[i]);
            } else if(str[i] == ' '){//为空格时
                if(!num.empty()){ //若数字不为空,则压入栈中
                    numStack.push(stod(num));
                    num.clear();
                }
            } else{ //此为+ - * /情况
                if(str[i]=='$'){
                    if(!num.empty()){ //若数字不为空,则压入栈中
                        numStack.push(stod(num));
                        num.clear();
                    }
                }
                while (!operStack.empty() && priority[operStack.top()] >= priority[str[i]]){//要弹栈
                    calculate();
                }
                operStack.push(str[i]);
            }
        }
        printf("%.2lf\n",numStack.top());
        numStack.pop();
        str.clear();
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
06-27 18:00
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
05-28 12:15
点赞 评论 收藏
分享
程序员牛肉:主要是因为小厂的资金本来就很吃紧,所以更喜欢有实习经历的同学。来了就能上手。 而大厂因为钱多,实习生一天三四百的就不算事。所以愿意培养你,在面试的时候也就不在乎你有没有实习(除非是同级别大厂的实习。) 按照你的简历来看,同质化太严重了。项目也很烂大街。 要么换项目,要么考研。 你现在选择工作的话,前景不是很好了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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