难点在于如何处理字母后面省略的系数1
#include<iostream>
#include<string>
#include<cctype>
#include<iomanip>
using namespace std;
double Molar(char c)
{
double M;
if (c == 'C') M = 12.01;
else if (c == 'H') M = 1.008;
else if (c == 'O') M = 16.00;
else if (c == 'N') M = 14.01;
return M;
}
int main(void)
{
int T, count, j;
double sum;
char ch;
string s;
cin >> T;
while (T--)
{
cin >> s;
sum = 0.0;
for (int i = 0; i < s.length(); i++)
{
ch = s[i];
if ((i + 1 == s.length() || isalpha(s[i + 1]))) count = 1;
else
{
count = 0;
for (j = i + 1; j < s.length(); j++)
{
//处理数字部分
if (isdigit(s[j])) count = count * 10 + (s[j] - '0');
else break;
}
i = j - 1;
}
sum += Molar(ch)*count;
}
cout << setiosflags(ios::fixed) << setprecision(3) << sum << endl;
}
return 0;
}