习题3-2 分子量(Molar Mass, ACM/ICPC Seoul 2007, UVa1586)
给出一种物质的分子式(不带括号),求分子量。本题中的分子式只包含4种原子,分别为C, H, O, N,原子量分别为12.01, 1.008, 16.00, 14.01(单位:g/mol)。例如,C6H5OH的分子量为94.108g/mol。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXN 85
#define C 12.01
#define H 1.008
#define O 16.00
#define N 14.01
int main(){
int T=0;
char s[MAXN];
scanf("%d",&T);
while(T--){
double sum = 0.0;
scanf("%s",s);
int n = strlen(s);
int i;
for (i=0;i<n;){
int cnt = 1;
if (isdigit(s[i+1])){
if (isdigit(s[i+2])){
cnt = (s[i+1]-'0')*10+(s[i+2]-'0');
}
else cnt = s[i+1]-'0';
}
switch (s[i]){
case ('C'):
sum += C*cnt;
break;
case ('O'):
sum += O*cnt;
break;
case ('N'):
sum += N*cnt;
break;
case ('H'):
sum += H*cnt;
break;
default:
break;
}
i += (cnt==1?1:(cnt>9?3:2));
}
printf("%.3f\n",sum);
}
return 0;
}