水题,直接分离出字母数字然后计算即可。注意判断分子量是一位数还是两位数。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#define maxn 101
int main()
{
int t;
char s[maxn];
scanf("%d",&t);
while(t--)
{
scanf("%s",s);
int cc = 0,hh = 0,oo = 0,nn = 0;
int l =strlen(s);
for(int i = 0;i < l;i++)
{
if(s[i] >= 'A' && s[i] <= 'Z' && ((s[i+1] >= 'A' && s[i+1] <= 'Z') || i == l-1))
{
if(s[i] == 'C') cc++;
if(s[i] == 'H') hh++;
if(s[i] == 'O') oo++;
if(s[i] == 'N') nn++;
}
if(s[i] > '0' && s[i] <= '9')
{
int num = 0;
if(s[i+1] > '0' && s[i+1] <= '9')
num = (s[i] - '0') * 10 + s[i+1] - '0';
else num = s[i] - '0';
if(s[i-1] == 'C') cc += num;
if(s[i-1] == 'H') hh += num;
if(s[i-1] == 'O') oo += num;
if(s[i-1] == 'N') nn += num;
}
}
printf("%.3lf\n",cc * 12.01 + hh * 1.008 + oo * 16.00 + nn * 14.01);
}
return 0;
}