题目链接如下:
我的代码如下:
#include <cstdio>
#include <string.h>
#include <cctype>
const int maxN = 81;
int T, temp, coef;
double ans;
double w[] = {12.01, 1.008, 16.00, 14.01};
char a[81];
int main(){
scanf("%d", &T);
while(T--){
scanf("%s", a);
ans = 0;
for(int i = 0; i < strlen(a); ++i){
if(a[i] == 'C'){
temp = 0;
} else if(a[i] == 'H'){
temp = 1;
} else if(a[i] == 'O'){
temp = 2;
} else{
temp = 3;
}
if(isalpha(a[i + 1]) || a[i + 1] == '\0'){
ans += w[temp];
continue;
}
coef = 0;
while(isdigit(a[i + 1])){
i++;
coef = coef * 10 + (a[i] - '0');
}
ans += coef * w[temp];
}
printf("%.3f\n", ans);
}
return 0;
}