题解 | #简单计算器#

简单计算器

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

#include <iostream>
#include <stack>
#include <iomanip>
using namespace std;
stack<char> opetor;
stack<double> digit;
bool isdigit(char x){
    if(x>='0'&&x<='9') return true;
    else return false;
}
double getdigit(string x,int& i){
    int r=0;
    while(isdigit(x[i])){
        r=r*10+x[i]-'0';
        i++;
    }
    return double(r);
}
int priority(char x){
    if(x=='#') return 1;
    else if(x=='$') return 2;
    else if(x=='+'||x=='-') return 3;
    else if(x=='*'||x=='/') return 4;
    else return -1;
}
double getvalue(double x,double y,char o){
    if(o=='+') return x+y;
    else if(o=='-') return x-y;
    else if(o=='*') return x*y;
    else return x/y;
}
int main() {
    string x;
    while(getline(cin,x) && x!="0"){
        opetor.push('#');
        x=x+'$';
        int i=0;
        while(i<x.length()){
            if(x[i]==' ') {
                i++;
            }
            else if(isdigit(x[i])){
                digit.push(getdigit(x,i));
            }
            else{
                if(priority(x[i])>priority(opetor.top())){
                    opetor.push(x[i]);
                    i++;
                }
                else{
                    double d2=digit.top();
                    digit.pop();
                    double d1=digit.top();
                    digit.pop();
                    double r=getvalue(d1,d2,opetor.top());
                    opetor.pop();
                    digit.push(r);
                }
            }
        }
        printf("%.2f",digit.top());
        cout<<endl;
    }
}

全部评论

相关推荐

屌丝逆袭咸鱼计划:心态摆好,man,晚点找早点找到最后都是为了提升自己好进正职,努力提升自己才是最关键的😤难道说现在找不到找的太晚了就炸了可以鸡鸡了吗😤早实习晚实习不都是为了以后多积累,大四学长有的秋招进的也不妨碍有的春招进,人生就这样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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