2017 计蒜之道 初赛 第二场 B.百度的科学计算器(简单)

来源:互联网 发布:咖啡豆品牌推荐 知乎 编辑:程序博客网 时间:2024/05/29 12:09

传送门


#include<iostream>//输入输出流#include<stack>//栈的头文件#include<cstring>//字符串函数#include<cmath>//数学函数#include<stdio.h>using namespace std;stack< char > q;//操作符栈stack< double > s;//数据栈double cal(double x, double y,char ch)  //四则运算{    if(ch=='+')        return x+y;    else if(ch=='-')        return x-y;    else if(ch=='*')        return x*y;    else        return x/y;}void oper()//两个数操作{    double a=s.top();    s.pop();    double b=s.top();    s.pop();    char op=q.top();    q.pop();    s.push(cal(b,a,op));}double pow1(double num,int n)//计算num的n次幂,其中n为整数{    double powint=1;    int i;    for(i=1;i<=n;i++) powint*=num;    return powint;}int main(){    int val[2000];    val['(']=3,val['+']=1,val['-']=1,val['*']=2,val['/']=2;//定义运算符优先级    string str;//储存表达式    int n;    int x=0;    int cnt=0;    cin>>n;    cin>>str;    str+='=';    int len=str.size(),j,flag=1;//初始化    double sum1=0,sum2=0;    for(int i=0; i<len; i++)    {        if(str[i]=='.')        {            x=1;        }    }    //for(int i=0;i<len;i++)       // cout<<str[i]<<endl;    for(int i=0; i<len;)    {        //操作符入栈和出栈        if(str[i]=='+'||str[i]=='-'||str[i]=='*'||str[i]=='/'||str[i]=='('||str[i]==')')        {            if(q.empty())//栈空就存就行了                q.push(str[i]);            else            {                if(str[i]==')')//匹配上一个‘(‘                {                    while(q.top()!='(')//出栈                    {                        oper();                    }                    q.pop();                }                else if(val[q.top()]>=val[str[i]]&&q.top()!='(')//优先级比较                {                    oper();                    q.push(str[i]);                }                else                    q.push(str[i]);            }            i++;            sum1=0,sum2=0,flag=1;        }        else if(str[i]!='=')        {            while(str[i]<='9'&&str[i]>='0'||str[i]=='.')//字符数字转化为double            {                if(str[i]=='.')                {                    j=0;                    flag=0;                    i++;                    continue;                }                if(flag==1)//小数点前                    sum1=sum1*10+str[i]-'0';                else//小数点后                {                    sum2+=(str[i]-'0')*pow1(0.1,++j);                 }                i++;            }             s.push(sum1+sum2);//数据入栈         }         else//清空栈         {             while(q.empty()!=1) oper();                              if(x==1)             {                 printf("%.6lf\n",s.top());             }             else             {                 long long num=s.top();                 cout<<num<<endl;             }             s.pop();             i++;         }     }     return 0; }


阅读全文
0 0
原创粉丝点击