分子式的化简

#include
#include
using namespace std;

const int maxn=1e2+7;
char str[maxn];
int main ()
{
    int n;
    double m[4]={12.01,1.008,16.00,14.01};
    while(~scanf("%d",&n))
    {
        scanf("%s",str);
        int num[4]={0};
        for(int i=0;str[i]!='\0';i++)
        {
            if(str[i]=='C')
            {
                if(isdigit(str[i+1])&&isdigit(str[i+2])) num[0]+=10*(str[i+1]-'0')+(str[i+2]-'0');
                else num[0]+=isdigit(str[i+1])?str[i+1]-'0':1;
            }
            if(str[i]=='H')
            {
                if(isdigit(str[i+1])&&isdigit(str[i+2])) num[1]+=10*(str[i+1]-'0')+(str[i+2]-'0');
                else num[1]+=isdigit(str[i+1])?str[i+1]-'0':1;
            }
            if(str[i]=='O')
            {
                if(isdigit(str[i+1])&&isdigit(str[i+2])) num[2]+=10*(str[i+1]-'0')+(str[i+2]-'0');
                else num[2]+=isdigit(str[i+1])?str[i+1]-'0':1;
            }
            if(str[i]=='N')
            {
                if(isdigit(str[i+1])&&isdigit(str[i+2])) num[3]+=10*(str[i+1]-'0')+(str[i+2]-'0');
                else num[3]+=isdigit(str[i+1])?str[i]-'0':1;
            }
        }
        double ans=0;
        for(int i=0;i<4;i++)
            ans+=(num[i]*m[i]);
        printf("%.3f\n",ans);
    }
    return 0;
}

这个题目比较简单 知道数字的最多的个数,所以相对来说是简单的。

你可能感兴趣的:(紫皮书(刘汝佳))