识别化学式,然后计算总值
1 #include <cstdio> 2 #include <iostream> 3 #include <cstring> 4 using namespace std; 5 double a[5]={0,12.01,1.008,16.00,14.01}; 6 char s[105]; 7 int t,len,cnt; 8 double ans,tmp; 9 void fuc(){ 10 ans=0; cnt=1; 11 for(int i=0;i<len;i++){ 12 if(s[i]=='C') tmp=a[1]; 13 else if(s[i]=='H') tmp=a[2]; 14 else if(s[i]=='O') tmp=a[3]; 15 else if(s[i]=='N') tmp=a[4]; 16 else { 17 cnt*=(s[i]-'0'); 18 while(s[i+1]<='9'&&s[i+1]>='0'){ 19 i++; 20 cnt*=10; 21 cnt+=(s[i]-'0'); 22 } 23 } 24 if(s[i+1]>'9'||s[i+1]<'0'){ 25 ans+=tmp*cnt; 26 cnt=1; 27 } 28 } 29 } 30 int main(){ 31 scanf("%d",&t); 32 while(t--){ 33 scanf("%s",s); 34 len=strlen(s); 35 fuc(); 36 printf("%.3lf ",ans); 37 } 38 }