习题3-2 分子量(Molar Mass, ACM/ICPC Seoul 2007, UVa1586)

时间:2022-10-28 06:31:45
#include<stdio.h>
#include<string.h>
#include<ctype.h>
double getweight(char x)
{
double m=0;
switch(x){
case 'C':m=12.01;break;
case 'H':m=1.008;break;
case 'O':m=16.00;break;
case 'N':m=14.01;break;
}
return m;
} int main()
{
int T;
scanf("%d",&T);
while(T--){
char s[100];
scanf("%s",s);
int i;
double t = 0;
int len = strlen(s);
for(i = 0;i < len;i++){
if(isalpha(s[i]) && isdigit(s[i + 1]) && isdigit(s[i + 2]))
t += getweight(s[i])*((s[i+1]-'0')*10 + (s[i + 2]-'0'));
else if(isalpha(s[i]) && isdigit(s[i + 1]))
t += getweight(s[i])*(s[i+1] -'0');
else if(isalpha(s[i]) && (!isdigit(s[i+1])))
t += getweight(s[i]);
}
printf("%.3f\n",t);
t = 0;
}
return 0;
}

1.字符串中的数字要减去0才可以计算