洛谷 第一次写这么麻烦的代码

P1022 计算器的改良

#include <bits/stdc++.h>
using namespace std;
char ch[1000000000],x;
double xs[1000000],cs[1000000];//统计系数和常数
int fh;//统计系数和常数的符号
int t=0,l=0;
int main()
{
    int j=0;
    fh=1;//等号左边默认初始符号为正数
    scanf("%s",ch);
    while(ch[j]!='=')
    {
        if(ch[j]=='+')
        {
            t++;
            fh=1;
        }
        if(ch[j]=='-')
        {
            t++;
            fh=-1;
        }
        if(ch[j]>='0'&&ch[j]<='9')
        {
            if(cs[t]==0)
                cs[t]=(ch[j]-'0')*fh;
            else
                cs[t]=cs[t]*10+(ch[j]-'0')*fh;
        }
        if(ch[j]>='a'&&ch[j]<='z')
        {
            if(ch[j-1]>'9'||ch[j-1]<'0')//保证当未知数前面的系数为1或-1时能够读入
            {
                xs[l]=fh;
                l++;
            }
            else
            {
                x=ch[j];
                xs[l]=cs[t];
                cs[t]=0;
                l++;
            }
        }
        j++;
    }
    t++,l++;
    j++;
    fh=-1;//等号右边默认初始符号为负数
    while(ch[j]!='\0')//与上面循环雷同,统计等号右边
    {
        if(ch[j]=='+')
        {
            t++;
            fh=-1;
        }
        if(ch[j]=='-')
        {
            t++;
            fh=1;
        }
        if(ch[j]>='0'&&ch[j]<='9')
        {
            if(cs[t]==0)
                cs[t]=(ch[j]-'0')*fh;
            else
                cs[t]=cs[t]*10+(ch[j]-'0')*fh;
        }
        if(ch[j]>='a'&&ch[j]<='z')
        {
            if(ch[j-1]>'9'||ch[j-1]<'0')
            {
                xs[l]=fh;
                l++;
            }
            else
            {
                x=ch[j];
                xs[l]=cs[t];
                cs[t]=0;
                l++;
            }
        }
        j++;
    }
    double res1=0,res2=0;
    for(int i=0; i<=t; i++)//等号右边只有一个字符时,t没有++
    {
        //cout<<cs[i]<<" ";
        res1=res1+cs[i];
    }
    //cout<<endl;
    for(int i=0; i<l; i++)
    {
        //cout<<xs[i]<<" ";
        res2=res2+xs[i];
    }
    //cout<<endl;
    //cout<<res1<<" "<<res2<<" "<<res1/(-res2);
    if(res1==0)//c++允许-0.000的情况出现
        printf("%c=0.000",x);
    else
        printf("%c=%.3lf",x,res1/(-res2));
    return 0;
}
发布了13 篇原创文章 · 获赞 0 · 访问量 393

猜你喜欢

转载自blog.csdn.net/qq_46126537/article/details/104054794