紫书上习题3-2,这道题我用的普通的 for 循环做的,逐个判断字符,若该字符为 C , H , O , N ,则判断该字符的后两位是否为数字,是数字就乘以该字符的原子量,最后求和;
v#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <iomanip>
#include <algorithm>
using namespace std;
int main()
{
char C,H,O,N;
string S;int n,p;
while(cin>>n){
while(n--){
cin>>S;
int len=S.length();double sum=0;
for(int i=0;i<len;i++){
if(S[i]=='C'){
if(S[i+1]>=49&&S[i+1]<=57){
if(S[i+2]>=48&&S[i+2]<=57)
p=10*(S[i+1]-'0')+(S[i+2]-'0');
else
p=S[i+1]-'0';
}
else
p=1;
sum=sum+12.010*p;
}
else if(S[i]=='H'){
if(S[i+1]>=49&&S[i+1]<=57){
if(S[i+2]>=48&&S[i+2]<=57)
p=10*(S[i+1]-'0')+(S[i+2]-'0');
else
p=S[i+1]-'0';
}
else
p=1;
sum=sum+1.008*p;
}
else if(S[i]=='O'){
if(S[i+1]>=49&&S[i+1]<=57){
if(S[i+2]>=48&&S[i+2]<=57)
p=10*(S[i+1]-'0')+(S[i+2]-'0');
else
p=S[i+1]-48;
}
else
p=1;
sum=sum+16.000*p;
}
else if(S[i]=='N'){
if(S[i+1]>=49&&S[i+1]<=57){
if(S[i+2]>=48&&S[i+2]<=57)
p=10*(S[i+1]-'0')+(S[i+2]-'0');
else
p=S[i+1]-'0';
}
else
p=1;
sum=sum+14.01*p;
}
else
continue;
}
cout<<fixed<<setprecision(3)<<sum<<endl;
}
}
return 0;
}