题解 | 简单计算器:建立运算符栈和运算数栈求解(注意字符串中各字符的处理)

#include <iostream>
#include <iomanip>  //用于cout输出限制精度
#include <string>
#include <cctype>  //用于检测字符串是否是数字
#include <stack>
using namespace std;

int priority(char c)  //判断优先级
{
    if(c=='#')
    {
        return 0;
    }
    else if(c=='$')
    {
        return 1;
    }
    else if(c=='+'||c=='-')
    {
        return 2;
    }
    else
    {
        return 3;
    }
}

double getnumber(string str,int& index) //确定数字的大小(以免有二位以上的数)
{
    int num=0;
    while(isdigit(str[index]))
    {
        num=num*10+(str[index]-'0');
        index++;
    }
    return num;
}

double calculate(double x,double y,char c)  //计算
{
    if(c=='+')
    {
        return x+y;
    }
    else if(c=='-')
    {
        return x-y;
    }
    else if(c=='*')
    {
        return x*y;
    }
    else
    {
        return x/y;
    }
}

int main() {
    string str;
    while (getline(cin,str)) {
        if(str=="0")
        {
            break;
        }
        stack<double> num;  //运算数栈
        stack<char> op;  //运算符栈
        op.push('#');  //栈底先加入一个优先级最低的字符用于比较
        int index=0;
        str+='$';  
/*字符串后加入一个优先级次低的字符,用于最后的计算,读者可模拟演练:如1+2,最后'$'字符会与'+'比较从而得到最终值*/
        while(index<str.size())
        {
            if(isdigit(str[index]))
            {
                num.push(getnumber(str,index));
            }
            else if(str[index]==' ')
            {
                index++;
            }
            else{
                if(priority(op.top())<priority(str[index]))
                {
                    op.push(str[index]);
                    index++;
                }
                else{
                    double y=num.top();
                    num.pop();
                    double x=num.top();
                    num.pop();
                    char c=op.top();
                    op.pop();
                    num.push(calculate(x,y,c));
                }
            }
        }
        cout << fixed << setprecision(2) << num.top();
    }
}

#考研复试机试上机个人解析##考研#
全部评论

相关推荐

04-28 11:34
西北大学 运营
牛客4396号:不好意思,这个照片猛一看像丁真
点赞 评论 收藏
分享
05-26 16:13
门头沟学院 C++
牢大肘击Java:海投就完事了bro,就当刷视频了
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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