#include<stdio.h>
#include<string.h>
#include<ctype.h>
#define maxn 100
char s[maxn];
#define LOCAL
float returnm(char c) //返回相对原子质量
{
if (c == 'C')
return 12.01;
else if (c == 'H')
return 1.008;
else if (c == 'O')
return 16.00;
else
return 14.01;
}
int main() {
#ifdef LOCAL
freopen("input.txt", "r", stdin);
#endif
int n = 0;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%s", s);
int len = strlen(s);
float tot = 0;
int j = 0;
while (s[j] != '\0')
{
if (isalpha(s[j]))
{
char current = s[j]; //当前字母
int weishu = 0; //字母后面的数字个数
int shu = 0; //统计字母后面具体数值
while (!isalpha(s[j + 1])&& s[j + 1]!='\0') //第一次提交时没有加上这个s[j + 1]!='\0'
{
weishu++;
j=j+1;
}
for (int k = 1; k <= weishu; k++)
{
shu = shu * 10 + (s[j + k - weishu]) - '0'; //每个元素的个数
}
tot = tot + shu*returnm(current);
if (weishu == 0) //如果字母后面没有数字
{
tot = tot + returnm(current);
}
j++; //使得下一个字符为字母或者结束符
}
}
printf("%.3f\n", tot);
}
return 0;
}
P57页。
先判断当前字符是否为字母,如果为字母,再判断其后是否为数字,然后把连续的数字字符转化成对应数字,current为当前字母字符。