思路就是将字符与数字分开
#include <bits/stdc++.h>
using namespace std;
const double C = 12.01, H = 1.008, O = 16.00, N = 14.01;
double divide(char * p ) {
double number[1000];
char s[1000];
double sum = 0.00;
int j = 0;
int l = strlen(p);
p[l] = 't';
p[l + 1] = 't'; //为了防止指针越界,对可能读取到的位置进行了初始化处理
for (int i = 0; i < l; i++) { //分离阶段
if (isalpha(p[i])) {
if (isalpha(p[i + 1])) {
s[j] = p[i];
number[j] = 1;
j++;
} else {
if (isdigit(p[i + 2])) {
s[j] = p[i];
number[j] = (p[i + 1] - '0') * 10 + (p[i + 2] - '0');
j++;
} else {
s[j] = p[i];
number[j] = (p[i + 1] - '0');
j++;
}
}
}
}
for (int i = 0; i < j; i++) {
switch (s[i]) {
case 'C':
number[i] = number[i] * C;
break;
case 'H':
number[i] = number[i] * H;
break;
case 'O':
number[i] = number[i] * O;
break;
case 'N':
number[i] = number[i] * N;
break;
}
}
for (int i = 0; i < j; i++) {
sum += number[i];
}
return sum;
}
int main() {
int l;
cin >> l;
getchar();
char atom[100];
while (l--) {
gets(atom);
double sum = 0.00;
sum = divide(atom);
cout << setiosflags(ios::fixed);//小数点要保留三位
cout << setprecision(3) << sum << endl;
}
}