题解:已知元素组成求解相对分子量,单个元素最多只有两位数两层if判断就可以了
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int n=256;
const int maxn=10001;
double mass[n];
int main()
{
memset(mass,0,256);
mass['C']=12.01;
mass['H']=1.008;
mass['O']=16.00;
mass['N']=14.01;
int t;
cin>>t;
while(t--)
{
string str;
cin>>str;
double sum = 0;
double temp;
for(int i=0; i<str.size(); i++){
if(mass[str[i]]){
if(str[i+1]>='1'&&str[i+1]<='9'){
if(str[i+2]>='0'&&str[i+2]<='9'){
temp=(str[i+1]-'0')*10+str[i+2]-'0';
sum +=temp*mass[str[i]];
i+=2;
}
else{
temp=str[i+1]-'0';
sum +=temp*mass[str[i]];
i++;
}
}
else{
sum +=mass[str[i]];
}
}
}
printf("%.3f
",sum);
}
return 0;
}