简单计算器遇到段错误,要哭了

用cpp实现一个简单计算器,在本地测试用例都很好,以提交就提示段错误,各路大佬们帮帮忙把
#include<stdio.h>
#include<stack>
#include<string.h>
#include<iostream>
using namespace std;
bool cmp(char ch1,char ch2)
{
    if((ch1=='*'&&ch2=='/')||(ch1=='*'&&ch2=='/'))
        return 1;
    else if((ch1=='*'||ch1=='/')&&(ch2=='+'||ch2=='-'))
        return 1;
    else if((ch1=='+'||ch1=='-')&&(ch2=='*'||ch2=='/'))
        return 0;
    else if((ch1=='+'&&ch2=='-')||(ch1=='-'&&ch2=='+'))
        return 1;
    return 1;
}
double caculate(double a,double b,char ch)
{
    if(ch=='*')
        return a*b;
    else if(ch=='/'&&b!=0)
        return a/b;
    else if(ch=='-')
        return a-b;
    else if(ch=='+')
        return a+b;
    return 0;
}
int main()
{
    char str[201];
    stack<double> sn;//数字
    stack<char> sc;//符号
    while(gets(str))
    {
        if(!strcmp(str,"0"))
           break;
        while(!sn.empty())
            sn.pop();
        while(!sc.empty())
            sc.pop();
        for(int i=0;i<strlen(str);)
        {
            if(str[i]>='0'&&str[i]<='9')
            {
                int num=0;
                while(str[i]!=' '&&str[i]!='\0'&&i<strlen(str))
                {
                    num=num*10+(str[i]-'0');
                    i++;
                }
                sn.push(num);
                i++;
            }
            else
            {
                if(sc.empty())
                {
                    sc.push(str[i]);
                    i+=2;
                }
                else
                {
                     while(!cmp(str[i],sc.top())&&!sc.empty())
                     {
                          char ch=sc.top();
                          sc.pop();
                          double b=sn.top();
                          sn.pop();
                          double a=sn.top();
                          sn.pop();
                          double ans=caculate(a,b,ch);
                          sn.push(an***r />                       }
                      sc.push(str[i]);
                      i+=2;
                }
            }
        }
        while(!sc.empty())
        {
            char ch=sc.top();
            sc.pop();
            double b=sn.top();
            sn.pop();
            double a=sn.top();
            sn.pop();
            sn.push(caculate(a,b,ch));
        }
        printf("%.2lf\n",sn.top());

    }
    return 0;
}


#笔试题目#
全部评论

相关推荐

04-25 18:13
五邑大学 Java
后来123321:大二两段实习太厉害了,我现在大二连面试都没有
点赞 评论 收藏
分享
不要停下啊:大二打开牛客,你有机会开卷了,卷起来,去找课程学习,在牛客上看看大家面试笔试都需要会什么,岗位有什么需求就去学什么,努力的人就一定会有收获,这句话从来都经得起考验,像我现在大三了啥也不会,被迫强行考研,炼狱难度开局,啥也不会,找工作没希望了,考研有丝丝机会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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