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

#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();
    }
}

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

相关推荐

06-18 15:03
门头沟学院 Java
至少实习看起来比去年好?问了下群里的同学和身边的同学,人均有offer。有的还有好几个大厂offer
菜鸟1973:上一年暑期也是人均大厂实习offer,结果秋招跟不招人一样,大部分都转正了
点赞 评论 收藏
分享
水墨不写bug:疑似没有上过大学
点赞 评论 收藏
分享
牛客848095834号:举报了
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-19 19:05
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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